texts:
I'm trying to find a smart way to store and retrieve stats for a tower defence game, but am currently unsure as to which approach would be best.

Description:

The stats system should quite basic, there are 4 different towers, with up to 5 different levels each.
One important requirement is that the stats should be stored in an XML file so that the game designer easily can access and balance the stats. (He knows nothing about programming)

I can see two ways of doing this:

By creating a TowerStats class which hold values for one type of tower for one level. Something like:

public class TowerStats2
{
    public TowerType type;
    public int lvl;
    public int damageLow;
    public int damageHigh;
    public float range;
    public float attackFrequency;
}

Then i would load the stats from the XMl file using Linq and XDocument and load it directly into a TowerStat List. I would do this for each tower so in the end there would be 4 different List's which would hold the different level stats for the specified tower.

gunTowerStats[0] would hold level 1 stats of the gun tower
rocketTowerStats[2] would be level 3 stats of the rocket tower

When a new tower is bought by the player or when a tower is upgraded, the stats would then be taken from the List so something like:

UpgradeTower()
{
    lvl++;
    towerStats = gunTowerStats[towerLevel - 1]
}

Alternativly I could hardcode all the values, and have one big class which would go something like this:

gunTowerDamageLvl1 = 4;
gunTowerDamageLvl2 = 8;
gunTowerDamageLvl3 = 15;
rocketTowerDamageLvl1 = 10;

you get the point.
I know that hardcoding is never never really the way to go. But does that also count for this kind of example where all possible tower attributes are known and will not change? the only thing that will change are the values of these attributes.

Question
I'm personally in favour of the first way, but I must admit that I find both ways a bit clumsy, would it be alright to do it one of these ways or is there a much smarter  and more obvious way to deal with this that I'm completely unable to see?

I hope my question is understandable.


texts: I have a video that is 360 degrees  across and approximately 30 degrees vertically.  Is there a way I can stitch this into a 360 video view-able with google cardboard or something similar?


texts: Is there a quick-reference card for HLSL (DX9 or DX11)?

texts:
Does anyone know of a DX9 or DX11 counterpart to the GLSL quick-reference card from Khronos?  The GLSL card is pages 8-11 here, and lists preprocessor directives, operators, types, and builtin variables and functions in a concise way.

I have looked here, on MSDN, and on Google results, including at the answers of this earlier question.  The closest I have found are:

Cg tutorial Appendix E, but that only covers the functions.
Adam Sawicki's cheatsheet, p.14, which lists predefined variables, but nothing else.
Ogre's wiki page on HLSL, which gives examples but not a reference.
The Ventuz shader node docs, which are close but are Ventuz-specific.

Context (and blatant plug ;) ) - there will be a Shader Showdown fragment-shader live-coding competition at Demosplash 2018 in Pittsburgh in a few weeks.  I am helping organize and would like the competitors to have reference cards so that more people can feel comfortable participating.  The software in question is Bonzomatic, which supports GLSL, DX9, and DX11 fragment shaders.  I can't give the GLSL competitors an unfair advantage, so if I can't find an HLSL quick-reference I will have to also not provide the GLSL reference.

I know this question may be on the edge of on-topic and appreciate your help.
 It is difficult to search for "quick-reference card" because "reference" materials are often very detailed (e.g., MSDN), and "cards" are more often hardware than paper in this context :) .  I have tried other search terms as well, but with limited success.


texts: How do I render Unicode characters that my font doesn't support?

texts:
How would I go about rendering all Unicode characters?

Most font files don't include characters like these.


texts:
I set -velocityX to my sprite gun.

float velocityX = -20 * dt;
if(trigger) {
   gun.setX(gun.getX() + velocityX);
}

I basically set a velocity of -20m/s to my gun vertex X. The problem is when I rotate the gun in a vertical position or example: 30degree angle.

How can I add recoil effect even if the sprite is not in a horizontal position, or should I just add it in the animation?


texts: How can I create a 2d procedurally generated circular maze like the following picture:


texts: Where should I place my reaction code in Per-Pixel Collision Detection?

texts:
I have this collision detection code:

public bool PerPixelCollision(Player player, Game1 dog)
{
    Matrix atob = player.Transform * Matrix.Invert(dog.Transform);

    Vector2 stepX = Vector2.TransformNormal(Vector2.UnitX, atob);
    Vector2 stepY = Vector2.TransformNormal(Vector2.UnitY, atob);

    Vector2 iBPos = Vector2.Transform(Vector2.Zero, atob);

    for(int deltax = 0; deltax < player.playerTexture.Width; deltax++)
    {
        Vector2 bpos = iBPos;
        for (int deltay = 0; deltay < player.playerTexture.Height; deltay++)
        {
            int bx = (int)bpos.X;
            int by = (int)bpos.Y;

            if (bx >= 0 && bx < dog.dogTexture.Width && by >= 0 && by < dog.dogTexture.Height)
            {
                if (player.TextureData[deltax + deltay * player.playerTexture.Width].A > 150 && dog.TextureData[bx + by * dog.Texture.Width].A > 150)
                {
                    return true;
                }
            }
            bpos += stepY;
        }
        iBPos += stepX;
    }
    return false;
}

What I want to know is where to put in the code where something happens. For example, I want to put in player.playerPosition.X -= 200 just as a test, but I don't know where to put it. I tried putting it under the return true and above it, but under it, it said unreachable code, and above it nothing happened. I also tried putting it by                bpos += stepY; but that didn't work either. Where do I put the code?


texts: Do I need a server to connect two players in a mobile game?

texts:
I would like to make a 2 players app game, where 2 players can compete with each other in real time.

If I want the player to be able to compete with the public (anyone who registered with my game able to compete with one another), do I need a server?

If I want the player to be only able to compete with his facebook friends, do I need a server?

Do I need a server at all in the first place, for 2 players game?


texts: Custom FPS Controller in Unity 5.6.6f2 not letting me look up or down

texts:
Due to the FPS Controller seeming to be broken in Unity now, I started using a custom one by kinifi on GitHub. For some reason though I can't look up or down. I removed the Main Camera so it should of fixed it but no. Is there anything I can change in this script to allow me to look up and down.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class FPS : MonoBehaviour
{

    private float speed = 5.0f;
    private float m_MovX;
    private float m_MovY;
    private Vector3 m_moveHorizontal;
    private Vector3 m_movVertical;
    private Vector3 m_velocity;
    private Rigidbody m_Rigid;
    private float m_yRot;
    private float m_xRot;
    private Vector3 m_rotation;
    private Vector3 m_cameraRotation;
    private float m_lookSensitivity = 3.0f;
    private bool m_cursorIsLocked = true;

    [Header("The Camera the player looks through")]
    public Camera m_Camera;

    // Use this for initialization
    private void Start()
    {
        m_Rigid = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    public void Update()
    {

        m_MovX = Input.GetAxis("Horizontal");
        m_MovY = Input.GetAxis("Vertical");

        m_moveHorizontal = transform.right * m_MovX;
        m_movVertical = transform.forward * m_MovY;

        m_velocity = (m_moveHorizontal + m_movVertical).normalized * speed;

        //mouse movement
        m_yRot = Input.GetAxisRaw("Mouse X");
        m_rotation = new Vector3(0, m_yRot, 0) * m_lookSensitivity;

        m_xRot = Input.GetAxisRaw("Mouse Y");
        m_cameraRotation = new Vector3(m_xRot, 0, 0) * m_lookSensitivity;

        //apply camera rotation

        //move the actual player here
        if (m_velocity != Vector3.zero)
        {
            m_Rigid.MovePosition(m_Rigid.position + m_velocity * Time.fixedDeltaTime);
        }

        if (m_rotation != Vector3.zero)
        {
            //rotate the camera of the player
            m_Rigid.MoveRotation(m_Rigid.rotation * Quaternion.Euler(m_rotation));
        }

        if (m_Camera != null)
        {
            //negate this value so it rotates like a FPS not like a plane
            m_Camera.transform.Rotate(-m_cameraRotation);
        }

        InternalLockUpdate();

    }

    //controls the locking and unlocking of the mouse
    private void InternalLockUpdate()
    {
        if (Input.GetKeyUp(KeyCode.Escape))
        {
            m_cursorIsLocked = false;
        }
        else if (Input.GetMouseButtonUp(0))
        {
            m_cursorIsLocked = true;
        }

        if (m_cursorIsLocked)
        {
            UnlockCursor();
        }
        else if (!m_cursorIsLocked)
        {
            LockCursor();
        }
    }

    private void UnlockCursor()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    private void LockCursor()
    {
        Cursor.lockState = CursorLockMode.None;
        Cursor.visible = true;
    }

}


texts: Creating single texture for all materials in substance painter with ID map. ID map doesn't bake properly

texts:
I am trying to create single texture for multiple materials in substance painter according to this tutorial. https://www.youtube.com/watch?v=HMP2xpGHimY

I have two models made in Blender. One with several materials(for generating ID map), another with one material.

Mesh for ID map:

Main mesh:

Both are totally identical from geometry and scale standpoint.

Generating ID map settings(it is a mobile game so I use only Unlit texture and don't require other maps and channels except for BaseColor):

Painting the model with masks created with ID map and actual problem.

Id map:

Model's materials in Blender (everything is great here):

How can I handle this issue?


texts: Customize Colors for Sprites in Web Game

texts:
So I'm working on an html5/javascript/css3-based game. Without going into too much detail, I'm thinking of having the characters be simple 8 or 16-bit style sprites, but I'd like to allow the user to customize the colors of their character.

Here are some examples of what I'm talking about :

http://jsfiddle.net/simurai/CGmCe/light/
http://www.splashnology.com/article/sprite-animation-in-css3/1485/

So the problem I'm having is two-fold:

1) Should I use something other than a sprite map for my characters, like actually draw them as shapes and animate them in a canvas element? That way I can fill the sprite with colors of the user's choosing? My fear there is that this would be inefficient as far as resources and also waste a lot of time hand-drawing everything, but could allow other customization (like height/width etc).

2) Are there potentially some web apis that would allow you to alter colors inside of a sprite? I suppose I could do it on the back-end with GD, but I'm trying to make it entirely in-browser (including local storage).

It's not a definitive one-answer only question, but I'm hoping someone can suggest something they've seen that approaches the same problem from another angle or gives us a way to customize the sprites or manipulate them in some manner. Or avoid them altogether, and use a different method.


texts:
I am struggling with designing black map and fog of war in a 3d game. Black map is the area that player hasn't explored (completely unknown), while fog of war is the area that player has explored and knows geospatial topology, but no friendly units or buildings are nearby to provide player with up-to-date info about enemy movements over the area.

The problem is that my terrain is 3D, varies in height greatly and camera can be placed at any position on the map at virtually any angle.

So far I've designed very heavy fog/clouds for area under fog of war, but not so heavy that the terrain underneath would not be visible, and am not rendering non-environment objects on those locations, but black map is another story.

Simply not rendering terrain over those locations looks and feels bad, and rendering terrain in pure black is not good as, when the camera is angled to view forward, player can still see elevation - very important information in the game and should not be given away without having to explore the map.

Are there any generally accepted ways of implementing such feature?


texts: Math > Logic for a Logarithmic Score Meter


texts:
I have some classic texture coordinates and as a normal behaviour they follow the mesh's transformations.

I am trying to use the same texture coordinates behaviour but without being affected by the mesh rotation transformation. The results would be a sort of texture coordinates projection.

I don't know if my explanations are well explained but how could I achieve such effect.

Thanks a lot.


texts:
I'm currently developing this rhythm game in lua (on top of a c++ engine) and I'm having trouble keeping a steady playhead position for the song currently playing.

The playhead position that the engine gives me updates in steps, so I get a fresh one every 2, 3 or 4 frames. But I need to have a steady one for sprites moving smoothly with the rhythm and stuff.

So I just keep track of my own playhead variable, which I initialize in 0 and then constantly add delta time to it. This variable eventually gets out of sync with the actual playhead, so every time I get a fresh playhead (or a "new step"), I correct my variable using the average between these two.

This however results in choppy movement.

I've seen many easing functions out there but I'm not sure which one would work in this case, nor when should I call it.

What would be the best way to ease my playhead variable into the stepped one?

This is the code I excecute every frame:

-- add delta to my own playhead variable

playhead = playhead + delta_time

-- if there's a new stepped_playhead value, correct my playhead

if stepped_playhead ~= last_stepped_playhead then
    playhead = (playhead + stepped_playhead) / 2
    last_stepped_playhead = stepped_playhead
end


texts:
Hello, can anyone tell me how can i implement backtracking in a a star search algorithm?
I've implemented the a star search according to wiki, but it does not backtrack, what i mean by backtrack is that if the open list(green cells) contains 2,0 and 3,3 as shown in the picture, upon reaching 2,0 the current node would "jump" to 3,3 since the cost is now more than 3,3 and continue the search from there, how can it be done so that it would backtrack from 2,0->2,1->2,2... all the way back to 3,3 and continue?


texts: How to evaluate a user against optimal performance?

texts:
I have trouble coming up with a system of assigning a rating to player's performance. Well, technically there is is a trivial rating system, but I don't like it because it would mean assigning negative scores, which I think most players will be discouraged by.

The problem is that I only know the ideal number of actions to get the desired result. The worst case is infinite number of actions, so there is no obvious scale. The trivial way I referred to above is to take score = (#optimal-moves - #players-moves), with ideal score being zero. However, psychologically people like big numbers. No one wants to win by getting a mark of 0. I wonder if there is a system that someone else has come up with before to solve this problem?

Essentially I wish to score the players based on:

How close they've come to the ideal solution.
Different challenges will have different optimal number of actions, so the scoring system needs to take that into account, e.g. Challenge 1 -> max 10 points, Challenge 2 -> max 20 points.
I don't mind giving the players negative scores if they've performed exceptionally badly, I just don't want all scores to be <=0


texts: Does GL Memory model guarantees that late Depth Testing accesses depth buffer values in same draw call

texts:
Suppose I issue a draw command that draws 3 overlapping triangles (T1, T2, T3). Fragment shader assigns Depth = 3 to T1 fragments, 2 to T2 and 1 to T3 fragments. Depth Buffer is cleared to 0 before draw call. GL Test is set to GL_Less.

Now, when pixels for triangle 2 are depth tested by the hardware, is it guaranteed that hardware will read the latest written values i.e 3 (by T1 fragments)?


texts: Graphics Raycast not returning GamObject Name

texts:
Here is my Graphics RayCast code:

void Update()

 {

if (Input.GetMouseButtonDown(0)) {

     PointerEventData cursor = new PointerEventData(EventSystem.current);
     cursor.position = Input.mousePosition;
     List<RaycastResult> objectsHit = new List<RaycastResult>();
     EventSystem.current.RaycastAll(cursor, objectsHit);
     Debug.Log(cursor.pointerPressRaycast.gameObject.name); //line 28
     }
 }

My Canvas settings has the "Graphics Raycaster" script enabled and all buttons are "RayCast target" enabled. The Canvas is of the "UI" layer, ignore reversed graphics is OFF and there are no blocking objects or blocking masks.

I receive the following error on runtime when selecting ANY canvas components:

  NullReferenceException: Object reference not set to an instance of an
  object CivilianUnitPlacement.Update () (at
  Assets/CivilianUnitPlacement.cs:28)

I'm unsure why this error is being generated. Looks like the RayCaster is registering a hit, so it baffles me that it cannot return the GameObject name at line 28.


texts: How can I interpolate between two frames of a sprite-based 2D animation?

texts:
For example, I'm looking to animate at 60 frames per second, but clearly my artist isn't going to hand-author 60 frames of art for every second of an animation clip and even if he could, it would only work properly in locked-timestep.

So given two successive frames in a sprite-based animation, I want to smoothly "interpolate" or "morph" between them at runtime to produce a smoother, and higher frame rate animation based on where the update time for the current frame lies between the two frames.

Another way to look at it would be to say that my animation is authored such that the frames occur at regular intervals, much less frequent then 60 FPS. Say I'm 30% between when frame N should appear and when frame N+1 should appear. I want to render an image that looks like it's a 30% the way through a smooth transition from the frame N image and the frame N+1 image.

This paper seems promising, but am interested in other potential solutions I could look at for implementing this. Please do not recommend a tool as a solution.


texts: Does GLSL copy function arguments by value?

texts:
My question is about passing variables to GLSL shader. I'm not sure how that works and what are the performance implications.

Say I got a function that accepts a "vec4" variable. The question is - is that variable copied at the entrance? I guess it makes impact on performance if so. And if it happens to be that way is there a way to pass only references like in C/C++?


texts: What is the convention for column-major order matrix transformations?

texts:
According to this cheat sheet for CG, if I want to use column-major order for my matrix/vector math I have to multiply from the left applying transformations from right to left, i.e. v' = P * V * v

I built my view and projection matrices like this

Matrix44 view(right.x, right.y, right.z, -position.x,
              up.x, up.y, up.z, -position.y,
             -forward.x, forward.y, forward.z, -position.z,
              0.0f, 0.0f, 0.0f, 1.0f)

Matrix44 projection(Sx, 0.0f, 0.0f, 0.0f,
                    0.0f, Sy, 0.0f, 0.0f,
                    0.0f, 0.0f, Sz, Pz,
                    0.0f, 0.0f, -1.0f, 0.0f);

However, when using them in the vertex shader

gl_Position = projection * view * vec4(position, 1.0);

I cannot see my geometry unless I swap the transformation to

gl_Position = vec4(position, 1.0) * view * projection;

which means that I am using row-major order instead of column order. So my question is if the pdf I'm following is correct in the notation for the column-major order for view and projection matrices or what am I missing?


texts:
I have a camera follow script which is attached to the main camera and it follows the players position and rotation. The player needs to be near the top of the screen. However when I hit play, the player  is shown at the center of the screen. This is how it looks in the scene view and this is how it should reflect when I hit play. Here the "y" position is -2 and "x" rotation is 0.

But when I press play, the "y" position is still -2 but "x" rotation changes to -14.9. And the player is shown at the center of the screen and not near the top.

Here is the camera follow script:
[SerializeField] Transform target;
public Vector3 defaultDist;
[SerializeField] float distDamp = .1f;

public Vector3 velocity = Vector3.one;

Transform myT;

void Awake()
{
    myT = transform;
}

void LateUpdate()
{
    SmoothFollow();
}

void SmoothFollow()
 {
    Vector3 toPos = target.position + (target.rotation * defaultDist);

    Vector3 curPos = Vector3.SmoothDamp(myT.position, toPos,ref velocity ,distDamp);
    myT.position = curPos ;

    myT.LookAt(target, target.up);
 }
}

After I hit play, I want the x rotation to stay at 0 and the player to be shown near the top of the screen. Can someone please help?


texts:
I have a prefab of a grid which contains 3 different tilemaps:

Main, Foreground, & Background

I want to reference the tilemaps inside a script of the prefab but can't figure out how to do that... I just need to edit the tiles in the tilemaps located inside the prefab.


texts: How can I find if a GameObject is not exist in the Hierarchy?

texts:
var selections = Selection.objects.OfType<GameObject>().ToList();
        if (selections.Count > 0)
        {
            tempSelections = selections;

            for (var i = selections.Count - 1; i >= 0; --i)
            {
                var selected = selections[i];
                transformSelection.Add(selected.transform);
            }

            TransformSaver.SaveTransform(transformSelection.ToArray());
            transformSelection = new List<Transform>();
        }

        for (var i = tempSelections.Count - 1; i >= 0; --i)
        {
            var selected = tempSelections[i];
            if (GameObject.Find(selected.name) == null)
            {
                GUI.enabled = true;
            }
            else
            {
                GUI.enabled = false;
            }
        }
        if (GUILayout.Button("Undo last selection if deleted"))
        {
            transformsCount = TransformSaver.LoadTransform().Length;
            PlayerPrefs.DeleteKey("transform");
        }

For testing I'm deleting one of the GameObjects in the tempSelections List

But then I'm getting exception in the editor on the line:

if (GameObject.Find(selected.name) == null)

Since the GameObject have been deleted it can't access the GameObject.

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.


texts: Why when rotating the character to the next target it's rotating to the other direction?

texts:
Instead rotating and facing the target it's rotating to the other side but moving to the target.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SoldierPatrol : MonoBehaviour
{
    System.Random rnd = new System.Random();
    public GameObject[] points;
    // assume you have 5 possible points that you can go
    public int moveIndex = 0;
    public float speed = 3;
    public float smoothSpeed = 0.5f;

    void Update()
    {
        Rotate(points[moveIndex]);
        transform.position = Vector3.MoveTowards(transform.position, points[moveIndex].transform.position, speed * Time.deltaTime);
        if (Vector3.Distance(transform.position, points[moveIndex].transform.position) < 1)
        {
            moveIndex = rnd.Next(0, 3);
        }
    }

    private void Rotate(GameObject target)
    {
        transform.rotation = Quaternion.Lerp(transform.rotation, points[moveIndex].transform.rotation, Time.deltaTime * 1);
    }
}


texts:
I am creating a basic XNA recreation of Minecraft. My current problem is that my "Steve" model, which is skinned with an armature using vertex groups to deform, is showing up disfigured beyond all reason. I am using a custom shader with skinning imported from the SkinnedEffect from the StockEffects example. I'm sure the effect itself works fine and that my model's groups and weights are the problem. A link to another forum with the same question is here, since I cant post pictures or more than two links.

Here are some details about my model: The version of Blender I use is 2.6. Pay no attention to the corner-looking piece. That's just there for size comparison when I built him. I export to .fbx with only the mesh and armature selected. No options are selected other than "Export Selected" and "Apply Modifiers". Smoothing is off, Forward is -Z Forward and Up is Y Up. Again, I think the problem is the vertex groups and wights. Everything deforms properly in Blender, but not in XNA.

My Custom Shader:

//VertexShader
VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
        VertexShaderOutput output;
        Skin(input, NumBones);
        float4x4 worldViewProj = mul(mul(World, View), Projection);
        output.Position = mul(input.Position, worldViewProj);
        float4 normal = mul(input.Normal, WorldInverseTranspose);
        float lightIntensity = dot(normal, DiffuseLightDirection);
        output.Color = saturate(DiffuseColor * DiffuseIntensity * lightIntensity);
        output.Color.a = 1;
        output.TextureCoordinate = input.TextureCoordinate;
        return output;
}

//Skin() Method
void Skin(inout VertexShaderInput input, uniform int boneCount)
{
        float4x4 skinning = 0;
        [unroll]
        for (int i = 0; i < boneCount; i++)
        {
                skinning += Bones[input.Indices[i]] * input.Weights[i];
        }
        input.Position = mul(input.Position, skinning);
}


texts: How could I remove part of a Terrain Collider?

texts: After reading through this site, I began to think on how could I remove the colliders of vertexes with a transparent texture on it? I had read a suggestion  (forgot where it was) to disable the whole terrain collider, but I also have NPC's, so having them plumet through the map wouldn't go over well.


texts: How to calculate angle for shooting bullet in 3D?

texts:
What I want to know is if I can calculate an angle similar to how I'm doing in 2D and update the x,y,z position of a bullet based on that angle in a similar manner I'm doing the update function below.

I wrote this function in Ruby to find the target angle between two 2D (x,y) vectors, but now I want to find out how to do this in 3D in a similar way:

  def target_angle(point1, point2)
    x1 = point1[0]
    y1 = point1[1]
    x2 = point2[0]
    y2 = point2[1]
    delta_x = x2 - x1
    delta_y = y2 - y1
    return Math.atan2(delta_y, delta_x)
  end

Given an object (like a bullet in this case), I can shoot the object given a target_angle between the player (x,y) and the mouse (x,y), as such in the bullet update function:

  def update
    wall_collision
    # the angle here is the target angle where point 1 is the player and
    # point 2 is the mouse
    @x += Math.cos(angle)*speed
    @y += Math.sin(angle)*speed
  end

Is there a similar method to calculate a target angle in 3D and use that angle in a similar manner as my update function (to shoot a bullet in 3D)? How can I make this work for two 3D vectors (x, y, z), where you have the player position (x,y,z) and some other arbitrary 3d point away from the player.


texts: Async loading in libGDX to set the screen

texts:
I would like to bring up a loading screen, for this would make the load async.
How can I do this? I looked on the libGDX website but I do not understand very well, maybe because of my poor English.

Here's the code :

public void show() {
        stage = new Stage();

        Gdx.input.setInputProcessor(stage);

        loading = new com.badlogic.gdx.scenes.scene2d.ui.Image(new TextureRegion(new Texture(Gdx.files.internal("loading.png"))));
        loading.setPosition(Gdx.graphics.getWidth() / 2 - loading.getWidth() / 2, Gdx.graphics.getHeight() / 2 - loading.getHeight() / 2);
        loading.setOrigin(loading.getWidth() / 2, loading.getHeight() / 2);
        loading.setZIndex(1);

        loading.addAction(rotateTo(1440, 20));

        stage.addActor(loading);

        game.setScreen(game.gameScreen);
    }

What I would do is an async method like this:

asyncmethod()

public asyncmethod()
{
     game.setScreen(game.gameScreen);
}

public void show() {
        stage = new Stage();

        Gdx.input.setInputProcessor(stage);

        loading = new com.badlogic.gdx.scenes.scene2d.ui.Image(new TextureRegion(new Texture(Gdx.files.internal("loading.png"))));
        loading.setPosition(Gdx.graphics.getWidth() / 2 - loading.getWidth() / 2, Gdx.graphics.getHeight() / 2 - loading.getHeight() / 2);
        loading.setOrigin(loading.getWidth() / 2, loading.getHeight() / 2);
        loading.setZIndex(1);

        loading.addAction(rotateTo(1440, 20));

        stage.addActor(loading);

        asyncmethod();
    }


texts: Attempting to have a group of units create random values independently in python 3 for a salvage loot system

texts:
I am working on creating a salvage mechanic for my game.  I want different units to calculate salvage after an encounter to randomly determine how much each one was able to scavenge from fallen allies or attackers.

As I have it setup up now its calculate as a group.
IE:  If I have group of units whom collectively can salvage value of 5 and for each point of salvage I can potentially gain 1-4 piece of salvage then I have a range of 5-20 pieces of salvage (provided there are 20 or more pieces of salvage to collect).  I am simply multiplying the total salvage value of the group by a randomly determined number in a range of 1-4.

My question is, how can I get each unit to calculate its salvage individually from its own range, rather than as a group as I'm doing now to give greater variance in the amount of salvage generated?

I am rather new and any suggestion or insight would be appreciated.

Below is the code for a demo I setup for the salvage system:

import random

parts_inventory = 0
undif_unit_count = 999
haulers = 2
foragers = 1
salvage_value = (haulers * 2) + foragers
temp_salvage = 0
salvage_random = random.randint(1, 4)

attack = random.randint(1, 6)
fatalities = attack
salvage_pool = fatalities * 4

print("There were {} units destroyed resulting in {} pieces of potential salvage".format(attack, salvage_pool))
print("Your units can haul away {} peice of salvage".format(salvage_value))

def salvage_operation(parts_inventory=parts_inventory):
    print("Encounter Haul {}".format(salvage_value))
    if salvage_value <= salvage_pool:
        print("You gained {} salvaged parts.".format(salvage_value))
        parts_inventory = parts_inventory + salvage_value
    if salvage_value > salvage_pool:
        print("You gained {} salvaged parts.".format(salvage_pool))
        parts_inventory = parts_inventory + salvage_pool
salvage_operation()


texts:
I'm looking for some references about water simulation, and how to model it's interaction with bodies (like boats, ships, submarines).

I've found a lot of references on the visual aspects of water (waves, reflection, etc), but very little about how to deal with the way it should interact with bodies. My experience with game development is very limited, and I'm really stuck here.

Bascally I would like to be able to make the position of a ship variates according to the waves. How can I do this?

I'm using Panda3D, but hope to hear about techniques and implementations used in any available technology.


texts: Are mobile devices a viable platform/market for "User-Generated Content"-based games?

texts:
I intend to do a lot of research into this, but I know this community has a knack for delivering hard-to-find gems of knowledge, so I figured I'd ask here first.

 Preamble (My Situation)

I'm currently looking into the viability of becoming an independent games developer by selling games for the mobile platforms (iOS and WP7 in particular). However, as I currently work full-time, all development has to be done in my own time (weekends, after-work, early mornings). Thus, I need to be careful with how I spend my time (I also have a social life to maintain). Basically, if I can release something that makes enough money, relative to my time investment into it, to be able to support myself with, I'll seriously consider taking the plunge.

The Question

One of the ideas I've had is for a game in a similar vein to Little Big Planet or Kodu, where the focus is on user-generated content, with the game itself providing a set of tools, samples and access to a 'market' for user-content.

What I envision is a simple set of drag and drop tools for placing content in levels, customising template assets, etc, and node-based editors for behaviour and logic (Think along the lines of Kismet, for those of you familiar with the Unreal Engine).

As a programmer, I've looked into this enough to know it is possible from a technical standpoint. However, what I need to know is if it is viable in terms of userbase. Is there a market for user-generated content games on the various mobile platforms?

Just to clarify, I'm not asking how to do it, I'm asking if it's worthwhile to do it.

EDIT
To reword the question and make it more answerable (given the lack of existing examples), what are relevant design considerations typically associated with the psychology of the mobile gamer that would influence the success of a game based on user-generated content?

EDIT 2
Microsoft have just released an app for WP7 called TouchDevelop that allows users to write executable scripts using a simplified tile-based interface. It's been downloaded a lot and garnered positive reviews. So, that's as strong of an indicator of community interest as I figure I'm ever going to get.


texts: VS code doesn't recognise new Unity Files

texts:
Vs code was working fine for some time, and suddenly it stopped supporting new unity c# classes

Also, there is no regenerate project files option in unity
I tried restarting unity and vscode, but no success....
Also, assemblyCSharp doesn't add new files to it....


texts: How to hide assets from user? ( e.g.: a png file )

texts:
I think the title is quite self-explaining, still this is a big area I think, so let me drop a few words:

I've got a simple experiment game project going, and I want to make sure, that the user isn't messing with the game assets like player skin etc.

In my opinion the best way would be that on production I would merge all the assets into one file and the application would check the hash of that file, so it could detect the corrupted data.

Is this an acceptable practice? There must be sum libraries / applications which are targeting this problem, could you guide me on this?

Project details: unix/linux, c++, sdl


texts: Calculate 3D "up" vector to align ship to an arbitrary axis

texts:
I'm writing a script to control the movement of a 3D ship in a game. Given the ship's position and the coordinates of the destination, I've successfully calculated the Yaw and Pitch necessary to aim the ship at the target.

The part I haven't figured out is Roll. In addition to the target coordinates, I'd like to specify that the ship's "up" vector be aligned on a particular axis (X, Y, Z, positive or negative). Since the target coordinates could be anywhere, the ship will never be perfectly aligned on an axis, but I'd like to calculate the "up" vector for the ship that is the closest it can get to being aligned to that axis.

Essentially, I want to rotate the ship to point at the target, and also ensure that the ship is "upright" relative to the target.

The closest I've gotten is something like this:

Vector3D upVector;  // The ship's normalized "up" vector
Vector3D rollVector = new Vector3D( upVector[0], upVector[1], 0 );
rollVector.Normalize();
float shipRoll = (float)Math.Acos( rollVector.Dot( new Vector3D(0, 1, 0) ) );
if ( upVector[0] < 0 ) {
    shipRoll *= -1;
}

This almost works, for certain axis, but not well enough. The ship rolls to approximately the right angle, but then rocks back and forth, trying to reach perfect alignment to the axis. Which is impossible given the ship's arbitrary rotation. I think I'm just not understanding it well enough.

I think what I need to do is calculate the correct vector, given the ship's rotation, and roll into that, rather than just trying to roll towards the axis itself. But how would I calculate that for an arbitrary axis?


texts: Unity Vector3.MoveTowards over the span of a minute with Time.deltaTime

texts:
I'm trying to figure out how to use Time.deltaTime to let me move an object over the course of a minute.

From my understanding, Vector3.MoveTowards(transform.localPosition, finish, Time.deltaTime) will result in transform moving to finish over the span of one second. The same function but with Time.deltaTime * 2 would result in the object completing the movement in the span of 30 seconds.

Therefore, I thought that Vector3.MoveTowards(transform.localPosition, finish, Time.deltaTime / 60) would cause the movement to happen over the course of 60 seconds. However, the move is extremely slow, and it looks like it would take several minutes to reach its destination.

I'm clearly using a wrong value somewhere, but what is it?


texts: Is Time.deltaTime different on various devices?

texts:
Can someone say what is wrong with my code. I have custom timer implemented like this:

 float timeRemain = 10f;
 void Update(){
 timeRemain -= Time.deltaTime;
 if(timeRemain <= 0){
  ///...code here.
   }
 }

On PC it runs like expected but on Android device timeRemain variable becomes 0 in less then 10 secs. Who can suggest me what happens when i run it on Android device?


texts:
https://docs.unity3d.com/ScriptReference/Plane-ctor.html

  public Plane(Vector3 a, Vector3 b, Vector3 c); Description: Creates a
  plane.

  The resulting plane goes through the given three points. The points go
  around clockwise as you look down on the top surface of the plane.

Since there is no Debug.DrawPlane I don't know whether my plane works as expected. Are all 3 Vectors world coordinates? Or are they connected to each other? Can somebody elaborate how this works? Neither can I make any sense of "The points go around clockwise as you look down on the top surface of the plane"


texts: Unity Animated Player Character Rotation Glitch

texts:
I was wondering if anyone experienced this issue in Unity with Mecanim-animated characters ...

I have an animated player character with a third-person camera control (Game Camera from the asset store, even though I think it isn't really related) and if the character is standing at the default y-rotation angle I can orbit around her with the camera and she will always face the same direction, as it should be.

But if the character stands with an arbitrary other transform y-rotation (for example 90.0001 or 180, etc.) and I orbit around the character, the character's Y rotation is ever so often randomly changed.

I don't know what changes the Y rotation. Game Camera doesn't touch it as long as I don't move the character so I suppose it is related to Mecanim, even though i'm not sure about that either.

I was hoping somebody has more familiarity with this issue and know what causes this. This glitch is definitely a problem in gameplay.


texts: How can I use one keycode key as toggle switch for two cameras?

texts:
using System;
using UnityEngine;
using UnityEngine.UI;
using Cinemachine;

public class CameraSwitch : MonoBehaviour
{
    public CinemachineVirtualCamera vcam;
    public CinemachineFreeLook fcam;

    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.V))
        {
            fcam.enabled = false;
            vcam.enabled = true;
        }
    }
}

When pressing on the V key it's switching between the cameras. I want that if I will press on the V key again it will switch between the two camera back fcam to be true and vcam to be false and so on each time pressing on the V key to switch between the cameras.


texts:
I'm currently trying to implement contour shading via edge detection on a depth texture.

I'm rendering the color and depth information onto two textures.
In my post processing shader I do the following:

out vec4 FragColor;
in vec2 TexCoords;
uniform sampler2D colorTexture;
uniform sampler2D depthTexture;
uniform float far;
uniform float near;

Then the matrices for the sobel filter:

mat3 sobel_y = mat3(
     1.0, 0.0, -1.0,
     2.0, 0.0, -2.0,
     1.0, 0.0, -1.0
);

mat3 sobel_x = mat3(
     1.0, 2.0, 1.0,
     0.0, 0.0, 0.0,
    -1.0, -2.0, -1.0
);

The function to linearize the Depthvalue

float LinearizeDepth(float z)
{
     float n = near;
     float f = far;
     return (2.0 * n) / (f + n - z * (f - n));
}

In the main I'm filling the matrix to calculate the gradients and then substract the result of the diffuseColor to get Black if the gradient is high (an edge) and just output the diffuseColor if the gradient is low.

void main()
{
    vec3 colorDiff = texture(colorTexture, TexCoords).rgb;
    mat3 I;
    vec3 texel;
    for (int i=0; i<3; i++) {
        for (int j=0; j<3; j++) {
            float depth = LinearizeDepth(texture(depthTexture, TexCoords + vec2(i-1, j-1)).r);
            I[i][j] = depth;
        }
    }

    float gx = dot(sobel_x[0], I[0]) + dot(sobel_x[1], I[1]) + dot(sobel_x[2], I[2]);
    float gy = dot(sobel_y[0], I[0]) + dot(sobel_y[1], I[1]) + dot(sobel_y[2], I[2]);

    float g = sqrt(pow(gx, 2.0)+pow(gy, 2.0));

    FragColor = vec4(colorDiff - vec3(g), 1.0);
}

My problem is that g is always 0 since i just the the normal color as output.

If i just output the depth values it does look correct:

Any Idea what I'm doing wrong here?


texts: Can a block-chain with embedded shared content stop cheating?

texts:
I want to make a game where users create their content and embed it in a block-chain. For example, they have a small x,y grid. In the grid they place objects... After the grid is made they share it via block-chain with others. The other players then experience this content and try to pass it unfairly. I feel like there is a way in the block chain to stop them via agreement or algorithm?
Is this possible?


texts:
With SDL TTF I've already gotten automatic line wrapping down using the built in "wrapped" function.

However, now I want to do what I guess you could call manual line wrapping. Basically, at certain points I want to start a new line.

Specifically, every time there is a open square bracket "[" I want to do a line ending, and continue the text on a new line. (The equivalent of hitting enter)

Any help would be awesome! (/n doesn't work with SDL TTF as far as I know)


texts: Best way to network the movement of 2D tanks?

texts:
I'm working on a multiplayer Flash game with a Python server and I have a quick question regarding how I should send positional updates for tanks for other players.

Should I choose

Option A:

When the player presses the move key, send the new velocity to the server and let the server calculate the new position per tick?

or

Option B:

When the player presses the move key, send the new position to the server and calculate the velocity clientside?

Which is the best option, in your opinion? What is most common? What will have less issues?

Other suggestions are welcome, I don't really know what I'm doing here. ;)


texts: Procedual terrain generation and biomes/predetermined variation

texts:
So I already have some (currently 2D possibly 3D later) simplex noise generation going, and with some experimenting I can make a map for plains, hills, mountains, etc

The problem now is I want to combine those together to create a larger more interesting map. For each "pixel" in the height map I provide/generate a biome type which has a bunch of parameters to define how the height value is calculated etc. i.e. I want to be able to say mountains here, river through there, flood plains next to it, etc and have them blend together.

The problem is this leaves nasty borders since between them even the simplex input values change suddenly (due to the x/z scaling being different, perhaps not the best way?). I considered just doing like a post process to smooth out the height values along the borders, but this would still leave often steep (and uninteresting near constant gradient) slopes since I could have a valley one side and a mountain peek the other side.

I am sure there must be a better fairly standard way to do this, but have not found much searching around, at least for this sort of noise function (midpoint displacement can be seeded with initial values at a low resolution, but doesn't seem viable if not generating the entire map at once)

double getHeight(int x, int z, Biome biome)
{
    double nx = x;
    double nz = z;
    nx *= biome.xzNoiseScale();//e.g. 1/64
    ny *= biome.xzNoiseScale();
    double noise = fbm(nx, nz, biome.noiseOctaves(), biome.noiseLacunarity(), biome.noiseGain());
    return biome.baseHeight() + noise * biome.heightVariation();
}

double fbm(double x, double z, int octaves, double lacunarity, double gain)
{
    double amp = 1;
    double freq = 1;
    double sum = 0;
    for (int i = 0; i < octaves; ++i)
    {
        sum += amp * noise(x * freq, y * freq);
        amp *= gain;
        freq *= lacunarity;
    }
    return sum;
}


texts:
I am learning shaders, and I figured I would try to use them to create sort of a predator effect.  I got to the point where I rendered my level to a rendertarget and passed that to the shader file, and attempted to get the color from it.  This, by my understanding, should render the player completely invisible from the code I have.  I have included relevant portions of my code.

Shader Code:

float4x4 World;
float4x4 View;
float4x4 Projection;

sampler s0;
texture land;
sampler land_sample = sampler_state{ Texture = land; };

float4 PixelShaderFunction(float2 coords: TEXCOORD0) : COLOR0
{
    float4 color = tex2D(s0, coords);
    float4 land_color = tex2D(land_sample, coords);

    if (color.a)
        return land_color;

    return color;
}

Main Draw Method:

protected override void Draw(GameTime gameTime)
{
    //First draw the level to the land rendertarget
    GraphicsDevice.SetRenderTarget(land);
    GraphicsDevice.Clear(Color.Black);

    spriteBatch.Begin(SpriteSortMode.Immediate, null, SamplerState.PointClamp, null, null, null, camera.Transform);
    levelOne.Draw(spriteBatch, gameTime);
    spriteBatch.End();

    GraphicsDevice.SetRenderTarget(null);

    spriteBatch.Begin();

    //Draw land
    spriteBatch.Draw(land, new Vector2(0, 0), Color.White);

    spriteBatch.End();

    //Draw the player and npcs normally
    spriteBatch.Begin(SpriteSortMode.Immediate, null, SamplerState.PointClamp, null, null, null, camera.Transform);
    npcs.ForEach(n => n.Draw(spriteBatch, gameTime));

    effect.Parameters["land"].SetValue(land);
    effect.CurrentTechnique.Passes[0].Apply();
    player.Draw(spriteBatch, gameTime);

    spriteBatch.End();

    base.Draw(gameTime);
}

Level Draw Code:

public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
{
    //Will cull tiles from level based on camera position later
    for (int i = 0; i < tiles.Length; i++)
    {
        for (int j = 0; j < tiles[i].Length; j++)
        {
            tiles[i][j].Draw(spriteBatch, gameTime);
        }
    }
}

Based on the tutorial I was following, this should replace the color in the player's sprite with that of the render target, but it does not.  Furthermore, the 'level' drawn in the player's sprite is scaled down a bit.

My question is why this isn't working?  Is there something I'm missing in the shader code?  Also, as a beginner shader learner please try to keep your responses rather simple, or point me to a reference.  Thanks!  :)


texts: UVW Unwrap multiple quads on same texture space automatically

texts:
I've been looking around the web for the answer to this question, but to no avail. So here I go.

I'm looking for a way to automatically map several quads on the same texture space (for example (0,0) ~ (0.4,0.4)) using the UVW unwrapper modifier of Max (or something else).

Here is a quick (and dirty) graphical explanation (click for larger):


texts:
Is there an algorithm for collecting the list of [to_spawn][to_despawn][to_send_movement] players from world on player movement from point A to B.

I have list of player in world.
I have function that collects the visible players for a given point.
Each player has a list of visible players.

How can I do this fast & efficient?

void p_spawn::filter(player_list &p_l)
{
    player_list to_depsawn;
    player_list to_spawn;
    std::shared_ptr<Node> temp = std::atomic_load(&head);
    if (p_l.size() > 0)
    {
        while (1)
        {
            if (!temp) break;

            bool in = false;
            for (size_t i = 0; i < p_l.size(); i++)
            {
                if (p_l[i]->eid == temp->p->eid)
                {
                    in = true; break;
                }
            }

            if (!in)
            {
                to_depsawn.push_back(temp->p);

                temp->p->spawn.add_erase(parent, false);
                add_erase(temp->p, false);

            }
            temp = temp->next;
        }

        for (size_t i = 0; i < p_l.size(); i++)
        {
            if (!inside(p_l[i]->eid))
            {
                add_erase(p_l[i]);
                p_l[i]->spawn.add_erase(parent);

                to_spawn.push_back(p_l[i]);
            }
        }
    }
    else
    {
        while (1)
        {
            if (!head) break;

            head->p->spawn.add_erase(parent, false);
            to_depsawn.push_back(head->p);
            head = head->next;
        }
    }

}


texts: Make Minecraft Main Menu Camera movement

texts:
I intend to make exactly like this. I highly suggest you watch just 5 seconds of the video because it already explains what I intend to do. I've been trying cosine and sine on vector3s but I can't seem to make it work since I usually get these results:

This however is my intended result:

This is my current code:
public class CameraWave : MonoBehaviour
{
    [SerializeField] float speed = 1f;
    // how deep and how wide the sine waves should be
    [SerializeField] float depthXY = 2f;
    // radius of the circle
    [SerializeField] float radiusZ = 10f;
    // makes the waves on the y axis and translates it
    [SerializeField] Transform targetLookAt;
    // parent of target look at so we can move it in the z direction
    [SerializeField] Transform lookAtContainer;
    // set angle to middle
    float angle = 0.35f;
    Vector3 cameraOffset;

    void Start() { cameraOffset = targetLookAt.position; }

    void Update()
    {
        // adjust angle
        angle += Time.deltaTime * speed;
        angle %= 360;

        // make cos-sine wave
        float x = Mathf.Cos(angle) * depthXY;
        float y = Mathf.Sin(angle) * depthXY;
        // set to look at
        Vector3 position = new Vector3(x,y);
        targetLookAt.localPosition = position;

        // update container to make it go in circles
        lookAtContainer.position = MakeCircleZ(angle) + cameraOffset;
    }

    Vector3 MakeCircleZ(float angle){
        Vector3 v = Vector3.zero;
        v.x = (radiusZ * Mathf.Cos(angle));
        v.z = (radiusZ * Mathf.Sin(angle));
        return v;
    }
}

My hierarchy setup:

any help is appreciated


texts: An efficient way for generating smooth circle

texts:
I'm looking for creating smooth circle. OpenGL supports point, line, and triangle. To create other primitives like circle, we utilize the preceding shapes. In my case, I've utilized points as follows:

float radius(0.5f);
for ( float angle(0); angle < glm::radians(360.0f); angle += glm::radians(0.5f) ){
    Vertex vertices[] = { Vertex(glm::vec3( radius*cos(angle), radius*sin(angle), 0)) };
    meshes.push_back(   new Mesh(vertices, sizeof(vertices)/sizeof(vertices[0]), 'P')   );
}

In rendering loop,

while( Window.isOpen() ){
    Window.PollEvents();
    Window.clear();
    //================( Rendering )=========================
    Shader.Use();

    for ( int i(0); i < meshes.size(); ++i )
        meshes[i]->draw();

    //======================================================
    Window.SwapBuffers();
}

The result is

Now to create smooth circle, basically I just increase the number of points. I don't like this approach since I need to create a lot of points for single shape. My question is is there an alternative yet efficient approach for this issue?


texts:
I have this little amusing game that I made in my second year of high school, and I'm rather impressed with it. It isn't anything that I could present in any style of major game conference or anything, it is simply a castle-defense I enjoyed creating greatly that got me through my programming course with highest grades. It is simply too small to do anything big with, I made the majority of it in a single week Easter holiday, but I still want to share it. It was made in C#, Visual Studio 2008, XNA 3.1. It can be played by either Xbox controller connected to the computer, or by keyboard. It relies heavily on XNA codes, I only thought of making things work so I saw it and not for everyone else. Now, my question.

If I want to share it, is this possible, where do I do it, and what should I expect for incidents? I am entirely new to the concept of sharing my game online, so I don't even know where to start. Is the game simply too old? Is there someplace similar to, like, Newgrounds except for XNA games? What could I possibly release the game for?

This kind of question must arise all the time, so I don't mind if I'm linked to some other question I've been unable to locate. All questions I've been able to find are asked before the people have even started the project, which is possibly smart. Me, I'm already done with this game and I'm wondering what I can do with it.

Anyone who can sate my curiosity?


texts: Converting Unity .fbx model to .stl using the exporter?

texts:
We bought this script asset from the Unity store. We need to run it to convert some .fbx files to .stl.
Is there any simple guide on how to run a script from the asset store?


texts: Should I store local forward/right/up vector or calculate when necessary?

texts:
I'm working on an object picking and translation/rotation/scale gizmos system in my engine where you select objects and perform transformations on them in a 3d editor-like fashion (e.g. Blender)

In my transform struct, I'm storing the position, rotation angle, rotation axis and a uniform scale value. When transforming my objects, I build the TRS matrix which forms my ModelToWorld matrix. All good.

Now I want to add the notion of local vs world translation. i.e. you select an object, and you can either move it along its local x axis, or the global x axis.

The global movement is easy I just add directly to my position vector. But for the local one, I have to build a local forward/right/up vector. e.g.

v3 GlobalUp = V3(0, 1, 0);
v3 LocalUp = m4_Rotate(Rotation->Angle, Rotation->Axis) * GlobalUp;

And then I translate my position by that amount:

Selection->Transform.Position += LocalUp;

I'm kind of torn whether I should store these local up/forward/right vectors in my transform (which means I have to calculate them once every frame in my update function, but every use of them after that point needs no calculation) or only when needed (no need to calculate every frame, but I have to call a function to do the calculation every time I need one, I could still keep the value in a local variable in my usage area if I'm using it more than once)

I'm not sure what approach to go with but I'm leaning towards calculating them as needed.

Are there any other pros/cons to each approach? or is this one of those things where there's no 'absolute right' way to do it?

Any advice is appreciated!


texts: Do Google/Apple provide the multiplayer servers for an app themselves?

texts: I have an app that I have been working on and I was wondering does Google/Apple host the server requirements for the multiplayer aspects of an app?


texts:
I'm trying to create a depth of field effect with bokeh sprites in GLSL. Specifically, what i would like to do is, for each pixel:

See if the pixel is out of the focal range
If it is, draw a quad and apply a texture to provide a bokeh sprite.

This kind of implementation is seen in the Unreal Engine and by Matt Pettineo, however, both implementations are in DX11 and I'm using OpenGL.

I'm a bit stuck on the drawing a quad and applying a texture bit. Does anyone know how I can do this, or provide any relevant links as to how I can do this?

Thanks


texts: I want to know if it were possible to integrate models created with Blender into a game written in solely C++.


texts: How can I increase the hit range of a node?

texts:
How can I set the radius or the hit range of a node initialized with a texture? Of course I can do that with increasing the size of it, but actually I want to do this without resizing the picture itself. This node is moving around the screen with a small speed. This is my code:

func addMonster() {

let monster = SKSpriteNode(imageNamed: "MosquitoDrawed")

monster.name = predatorNodeName

monster.zPosition = 1

// monster.physicsBody = SKPhysicsBody(circleOfRadius: 50.0)

monster.position = CGPoint(x: random(-10.0,max: -30.0), y: random(10.0, max:130.0))

addChild(monster)

let actualDuration = 7.0

let actionMoveTo = SKAction.moveTo(CGPoint(x: random(500, max:800),y: random(1, max:800) ), duration: NSTimeInterval(actualDuration))

monster.runAction(actionMoveTo,withKey: "move")

}


texts: Mechanim "Hand Closing / Opening" Animation control with trigger

texts:
I wish to control any given Animator state "Playhead", with a variable - rather than have it play automatically with time. This is for an animation of a hand making a "clench gesture" which will be bound to an analog controller trigger output value.

I have considered the following:

Inside: StateMachineBehaviour.OnStateUpdate method (State machine behavior script attached to a state in the Mechanim graph)

Call Animator.Play or Animator.CrossFade to play a given clip from a given time with speed set to 0. This should get called every update while in the state.

The issue with this is that the whole state will stop, then start again which means OnStateEnter and OnStateExit continually fire, rather than just the OnStateUpdate method to control the "Playhead".
Animator.ForceStateNormalizedTime(time)

This would be fine but it has been depreciated.
Use timers and the Animator speed variable to calculate when to toggle playing a clip at a certain speed such to match the displacement of the trigger. Seems the wrong way to go about it.
Use the legacy animation system

This works fine but you don't get the perks of Mechanim FSM eg. blend trees.

Since Unity seem to have removed the ability to manipulate the time of a running clip or Mechanim state, it makes me think it's something I shouldn't be doing. Am I going about this the wrong way? Why does it seem difficult to play an animation via something other than the time domain?


texts:
How do I count how many diamonds my player has collected in my 3d world
What I need to do is to make a script which will update my text ui when the player collides with a diamond but I do not know how as I auto generate the diamonds
How could I go about writing a script that will update the text score
What I tried so far, but I'm not sure where to place it. (taken from comment)
void OnTriggerEnter(Collider other) {
   if (other.CompareTag("Diamind")) {
      Debug.Log("Picking up...");
      GetComponent<Counter>().ScoreAmount += 1;
   }
}


texts: I'm trying to learn the "digital physics" required to do a floating network of spheres

texts:
If that is even what it is called.  What I am trying to do it:
http://asterisq.com/products/constellation/roamer/demo

Can someone please point me to towards a book or in vaguely the right direction?  I don't even know where to start or what physics/maths to read about?


texts:
Currently I'm writing an iOS game where the basic movement is rolling. Technically you make the player turn clockwise or counterclockwise. When you tilt the device to the right, you will rotate clockwise. This makes sense, because you are standing on a floor, so this will make you roll right. Same idea goes for left, of course.

But sometimes, the player can roll in some sort of looping. The problem with that is, is that the player is in contact with something above (in other words, with a ceiling). This makes the logic turn: tilting the device to the right, makes your rotate clockwise, which will cause you rolling to the left instead.

Physically this is okay for me. But I've seen lots of people trying my game getting confused about it. As they go into the loop, they turn the device the other was as well, in order to follow the direction of the loop. But that makes them roll the other way and slow down, and eventually drop.

I don't want to do a stupid check like: if touching at the top side, then reverse the control, because to me that feels not natural. So, I guess there are lots of other people with the same feeling to this as I'm experiencing.

So, my question is: Are there any good techniques of handeling this issue? Make it feel natural most of the time for everyone?


texts: I have made a ragdoll and attached (as child object) the main camera to it, but the camera doesn't follow the ragdoll. Why is this happening? And how do I fix this?


texts: Must I worry about quad-based rendering in real world scenarios?

texts:
Most of the time in the first chapters of a random book about rasterization and rendering techniques, I find some phrases about a triangle-based rendering system and a quad-based one.

I have never encountered a quad-based GPU or pipeline. Do I have to worry about that when dealing with OpenGL 3.0+, or is it just legacy stuff?


texts: Circle-Rectangle collision velocity adjustment

texts:
I created my circle vs. rectangle method based on this algorithm:

https://stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection

Currently, I have a dynamic ball with velocities c1SpeedX (for X axis) and c1SpeedY (Y axis). The dynamic ball is supposed to bounce off of the static rectangle when a collision occurs.

The boolean method that I use to detect if the intersection happened is the following:

        public boolean intersects (Circle circle, Rectangle rectangle) {
            double dx = Math.abs(circle.getLayoutX() - rectangle.getLayoutX());
            double dy = Math.abs(circle.getLayoutY() - rectangle.getLayoutY());

            if (dx > rectangle.getWidth() / 2 + circle.getRadius()) {
                return false;
            }
            if (dy > rectangle.getHeight() / 2 + circle.getRadius()) {
                return false;
            }

            if (dx <= rectangle.getWidth() / 2) {
                return true;
            }
            if (dy <= rectangle.getHeight() / 2) {
                return true;
            }
            double cornerX = (dx - rectangle.getWidth() / 2) * (dx - rectangle.getWidth() / 2);
            double cornerY = (dy - rectangle.getHeight() / 2) * (dy - rectangle.getHeight() / 2);

            double cornerDistance = cornerX + cornerY;
            double radii = circle.getRadius() * circle.getRadius();

            return cornerDistance <= radii;

        }

Once a collision has happened, my natural response would be to invert the values of X and Y, so the ball bounces off of the rectangle. The problem is that it's incredibly inaccurate, and the ball often goes through the rectangle without detecting a collision.

if (intersects(circle1, rect1)) {
                    c1SpeedX = c1SpeedX * -1;
                    c1SpeedY = c1SpeedY * -1;
                }

So, how do I optimize my code to make the ball always accurately bounce off of the rectangle? Is it a velocity problem, or is something wrong with the intersects method?

Thanks.


texts: I am working on the generation of Hexahedral mesh generation using octree based discretization. I have a volume mesh (Hexahedral), using isomorphism I need to project the outermost surface vertices of inner mesh onto original mesh. Could anyone help me on how to extract the surface of inner mesh?


texts:
I have the following in my update funtion. The first input for key_enter when textPos!=2 works fine, but the one when textPos==2 doesn't work. The key up and down work fine though.

The System.out.println("Enter: " + choice); never gets printed

public void update() {
        Input input = gc.getInput();
        if (input.isKeyPressed(Input.KEY_ENTER)) {
            if (textShowing && textPos != 2) {
                textPos++;
                textShowing = false;
            }
        }
        if (textShowing && textPos == 2) {
            if (input.isKeyPressed(Input.KEY_ENTER)) {
                System.out.println("Enter: " + choice);
                if (choice == 0) {

                } else if (choice == 1) {

                } else {
                    textPos++;
                    textShowing = false;
                    System.out.println("Text Pos: " + textPos);
                }
            } else if (input.isKeyPressed(Input.KEY_UP)) {
                if (choice > 0) {
                    choice--;
                }
            } else if (input.isKeyPressed(Input.KEY_DOWN)) {
                if (choice < 2) {
                    choice++;
                }
            }
        }
    }


texts:
In my app I need a file that I can keep settings like: TutorialSkip: True or AppDev: False and other info. How can I make this file and prevent users editing it?

This has to work in the Core folder for my project as it should work with android windows and ios.


texts: How to activate GearVR Menu in my own Unity-Apps?

texts: So in normal GearVr-Apps, which you can download from the marketplace, you can activate the GearVr Menu to control brightness etc. with a long click on the back button. But this does not work for all of my apps which I made with Unity for the GearVr, is there something special I have to import into my project?


texts:
I'm making a game that is a bit of a mix of snake and pacman.

Basically, two players go through the maze and each time they pick up a piece of candy, a cube is added to their tail.  If one player touches the other's tail, he steals that piece for himself and the game is over when one player has all the pieces.

Right now they both move randomly unless there's a piece of candy one space away that is not their tail.

I'm trying to find a method/algorithm (preferably a different method for each player) for both players to target/avoid the other player.
Any advice?


texts: Cell height with heightmap for collision detection

texts:
Hello everyone I'm programming a game with c++ and openGL. My world is generated from a heightmap (100x100 matrix with values 0-255) and now I need a function that returns the actual height based on which triangle of the heightmap I am.
I wrote this code

float Terrain::getCollisionHeight(float x, float z) {
    float x_pos = x / lato;
    float z_pos = z / lato;

    float _x = x-x_pos;
    float _z = z-z_pos;

    float m = _x / _z;

    float hp0 = hm->getHeight(x_pos,     z_pos)     / divider;
    float hp3 = hm->getHeight(x_pos + 1, z_pos)     / divider;
    float hp2 = hm->getHeight(x_pos + 1, z_pos + 1) / divider;
    float hp1 = hm->getHeight(x_pos,     z_pos + 1) / divider;
    cout << "HP: " << hp0 << " " << hp1 << " " << hp2 << " " << hp3 << endl;
    if (_x >= _z) {
        cout << "Upper triangle" << endl;
        float zp12;
        if (_z == 0) zp12 = lato;
        else zp12 = m*lato;
        float i1 = hp1 + (hp2 - hp1)*zp12/lato;
        return hp0 + (i1 - hp0)*_z / sqrt(0.5*0.5 + zp12*zp12);
    } else {
        float xp23;
        if (_z == 0) xp23 = lato;
        else xp23 = m*lato;
        float i1 = hp2 + (hp3 - hp2)*xp23 / lato;
        return hp0 + (i1 - hp0)*_x / sqrt(0.5*0.5 + xp23*xp23);
    }

but it returns wrong values (e.g. when i interpolate 135 and 117 it returns something like 140 which is greater than both of them).
The cases are separated because i always draw two triangles merged as a square.
Can you help me returning the right interpolation value? Thanks a lot


texts:
Some of you probably know the (once) popular mobile games Temple Run, Minion Rush or Subway Surfers. They all have the similarity of a lane system, which allows you to switch your position with a simple swipe to the left/right.

I am creating a game that also consists of three lanes. The only difference is your general movement going from left to right, thus making the lanes on top of each other.

As LibGDX is my preferred 2D games framework, I want to accomplish this task with mostly built-in functionality. Currently, I have two approaches, which both have flaws and resolving any of them would be a major help to me.

1) Using Actions. I could add an moveTo(upperLane.x, upperLane.y, 0.5f) if the player is in the middle, same goes for the lowerLane. But what, if he double swipes down, while being at the top? I would need so build a sequence, after the first actions started, or cancel the current action and start a new, but how to calculate the appropriate time for that large movement, while still "hanging between" two lines?

2) Implement impulses, that are able to add up in positive (up) and negative (down) directions. This would make it possible to move two steps at once, while having an appropriate time and also to move back up, while being in between two lanes, on your way down. Everything about impulses is plain speculation, as I have no further knowledge and don't want to use Box2D only for this purpose.

3) Feel free to give better suggestions! Special thanks to whom can point out the mechanic of one of the above mentioned games, which implement this feature flawlessly!


texts: Running multiple game servers on single host

texts: I want to use a vps/dedicated server for game hosting. I expect hosting a lot of servers on that. For the connection, should I assign a unique port for every server or change IPs for every server. And how would these 2 options impact on the game, if I had multiple vps/dedicated servers.


texts: Unity 3D Vive Focus conversion difficulties

texts:
I Keep getting this error message below when I try to build and run the game. I have downloaded sdk package:        sdk-tools-windows-4333796.zip Android studio. I am new to this kinda technology any help will be appreciated. The VR device is Vive Focus.

error Message below:
Extracting from
com.htc.vr.samples.hellovr.unity manifest:

miniWaveSDKVersion is Null!
NumDoFHmd is Null!
NumDoFController is Null!
NumController is Null!

Please ensure that these metadata in your
manifest matches the capabilities of your title.
This metadata will affect how viveport store distributes and displays your title


texts: Using a vector to store multiple instances of a class

texts:
To warm up with SMFL, I am creating a simple Block Breaker game. For the blocks and balls, I would like to store them as "instances" in a vector so that they can be added/removed with ease.

However, the compiler spits out an error when attempting to access the vector.

block.h

class Block {
private:
    bool dead;

public:
    Block();
    bool isDead();
    static std::vector<Block*> blockList;

    float x;
    float y;
};

main.h

#include "Block.h"

Block playerBlock;

main.cpp

#include "main.h"

int main()
{
    playerBlock.x = 50;
    playerBlock.y = 20;
    Block::blockList.push_back(&playerBlock);
    return 0;
}

When compiling, Xcode spits out the following error:
Undefined symbols for architecture i386:
  "Block::blockList", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Any help is welcome. This is not all of my src but it is all of the src related to the problem at hand.


texts:
I am working with animations in Unity and so far I have made only four (Up Down Left and Right) and my animation window looks following...

Problem is that if I was moving Up I want hero to stay looking Up not go to 'neutral idle' (or however he started), but that means I have 4 Idle positions... and each of them can transition to Up, Down, Left or Right and they go exponentially with each additional action...

Which makes me feel like I am doing something wrong....

Is there a better way of making transitions between different actions?


texts:
I have a character which has a size of 32x64 when walking or standing. Using the libgdx animation class I can easily animate him with a texture atlas.
When I want to make him attack however, the Sprite appears squished because the frames for the attack animation are 64x64 to accommodate the sword.
My question is as the artist and programmer, would it make more sense to have each Sprite frame for every animation be 64x64? Or in code, resize the Sprite origin and bounds before the attack animation and set them back to 32x64 when the attack is done?


texts: How can I simulate a floating character in Box2D?

texts:
I am creating a jump'n'run game using the Box2D physics engine. The main character should be a robot like creature without legs, floating over the ground powered by a jet engine.

The motion should look like that of a flying saucer: The creature never touches the ground, but also never gets too far from it. What construction of joints, shapes and bodies can do that nicely?

I started by trying to make a kind of pendulum:

     O        <-- head
     |
    +-+
    |X|       <-- creature's body
    +-+
 ----+-----   <-- ground (pendulum crossing)
     |
     O        <-- heavy body, weld joined to the creature, it does
                  collides with nothing, just pulling the creature
                  down to keep it upright

However, that isn't working smoothly and the creature bounces around too much. Besides, how can I simulate the jet engine nicely?


texts: Monogame Move objects while having a moving 2D camera

texts:
I am writing my first game. In this game, I have a heroEntity object, which has fields:

float X {get; set;}
float Y {get; set;}
Monogame.Extended.Camera2D Camera {get; set;}

Since I have some background, I use Camera.Move() instead of moving my heroEntity object (which I put at the center of the Camera.BoundingRectangle after each frame)

Now, I also a List<BulletEntity> Bullets (those bullets also have X and Y properties) and they should also move independently of the heroEntity.Camera object. When I simply implement movement of the camera and bullets independently, there is an impression that my bullets are kind of shaking.

How can I fix that?


texts: How to automatically destroy a gameobject after a method or block of code

texts:
In Unity I frequently find myself doing this in C#:

GameObject myObject = new GameObject();
try{
// do something with that object
}
finally{
   Destroy(myObject);
}

A good example is creating a temporary pivot point for another object.  I create the object, parent whatever object I want to rotate, do the rotation, then destroy the object.  It's in a finally block so in case anything goes wrong it still destroys the object.

Does Unity have any elegant way to do this?  Writing this all the time is tedious, and it's easy to forget the Destroy method at the end.


texts: Random tile-based floor plan generation with enclosed rooms

texts:
I've been working on a project for a while which takes a grid of n*n tiles (starting at n=16 and with n increasing by 4 every so often for new floors), and fills it with rooms of random rectangular sizes, and have been having issues creating an efficient algorithm to do so that fits my requirements:

The outside ring (where x = 1 or n | y = 1 or n) must be corridor tiles (obviously easy)
All rooms must be entirely surrounded by corridor tiles
In no place may there be a 2x2 grid of corridor tiles (so corridors are all 1 tile thick)
There are certain rooms of specific sizes that must be present, and then there are other types of rooms which just fill in the remaining space afterward.
Do not have any corridors that go all the way through the floor.
(Preferably) Room min side length = 2 (relatively easy to program in my code, perhaps not in one of 'your' suggestions)

My algorithm works fine, however at n=12 it takes ~2s to compute on my 4790k, and grows ridiculously exponentially from there: taking 6s for n=14, 29s for n=16, etc... Because there are two particular shapes whose creation must be avoided, as once created they make it impossible to fill up the grid entirely, and so my logic must make sure that doesn't happen, which leads to the performance issues.

My code is far too long to post here, but essentially what it does is:
Go through each 'open tile' (tiles that are not in rooms nor that are a corridor), find the maximum size it can be, then for loop through that size's x and y, see if a room at that x and y would create any of the aforementioned 'illegal' shapes, and if not, add this open tile and this open tile's size to an array of possible sizes and size positions.
I then choose a random size (more or less) from the list, and then create a room there.

Here is an example picture (though some seeds are better than this one) of what my algorithm results in:

Looking all over the internet I haven't been able to find an algorithm that fits my needs - mainly in the 'no corridors going through entire grid' issue.
(This issue is present in the picture I attached due to the smallness of n=12, the larger the grid, the less likely this occurs with my code - the issue is there are some algorithms, like what I am calling the 'recursive' method - ~halving all sectors that are larger than minimum size until done, which will always have at least one, no matter how large, ie...)

(n=64 with recursive method, minSize = 2, maxSize = 4)


texts: How to create walking animations in Gamemaker 8

texts:
We are learning how to use Gamemaker 8.1 in my game design class, and I wanted to experiment with it, and try to make my own game.
I have run into a problem when trying to animate an object walking.
I've looked all over google for how to animate the walking, but the only tutorials I can use what looks like a different kind of Gamemaker where you code everything.

To specify, I am using the version of Gamemaker where you drag and drop different actions into events. You can add code, but I would prefer not to use it.

I would like to know a way to either import a sprite sheet or a gif and have a walking animation play while the character is moving whenever you use the arrow keys.


texts: What is Google Play Services Multiplayer?

texts:
This question might be off-topic, i don't know where should i ask it.

What's the difference between Google Play Real-Time Multiplayer, Google Play Turn-Based Multiplayer and sockets?


texts: Directx 12 Root signature compatibility with pso

texts:
Can you bind a different root signature than the one that pipeline was created with? If so does it have to have exactly the same parameters or could it have like one more but the pipeline will ignore it?

Btw why is there no dx12 tag?


texts:
I'm trying to understand the Send Message Function but I'm a bit confused. Currently I have a game object character and I want it to send a message to the main body if one of its children hits something.

On the Child object, I have:

void OnTriggerEnter2D(Collider2D col) {

    Destroy(col.gameObject);
    Debug.Log(this.name + " Hit!");
    gameObject.SendMessage("PlayerHitting", this.name);

On the Parent Object, I have

public void PlayerHitting(string Move) {
    Debug.Log("Player hits with " + Move);
}

The Destroy code and Debug.Log on the Child work, so it is colliding, but I keep getting an error that there is no reciever.

SendMessage PlayerHitting has no receiver!
UnityEngine.GameObject:SendMessage(String, Object, SendMessageOptions)

I don't quite understand how to use Send Message to send messages and notices between objects. Can someone explain?


texts: The library I am using (SDL2) only supports drawing to int positions. I am currently storing my objects positions as double, and would like to render them. Should I round the value to int, i.e. 0.5 => 1, or simply cast it to int, i.e. 0.5 => 0?


texts: Is it legal to imitate a game without publishing it

texts:
If you're developing a game that's very similar to a game that's already published, both the game mechanics and the graphics but you're not publishing it, instead you're keeping it in your own computer.
Is it legal to do so?


texts: Unexpected positioning when programmatically instantiating objects in Unity?

texts:
I'm creating a simple match three game in Unity. I've opted to use Unity's UI system as it takes care of resolution scaling for me. The project is quite simple, at runtime I am programmatically creating an 8x8 grid of tiles via the script below. This script is attached to an empty Game Object residing within a canvas.
public class GameBoard : MonoBehaviour
{

    public int BoardSize = 8;
    public List<GameObject> TileSet;

    void Start ()
    {
        for (float y = 0; y < BoardSize; y++)
        {
            for (float x = 0; x < BoardSize; x++)
            {
                int tileIndex = Random.Range(0, TileSet.Count - 1);
                Vector3 position = new Vector3(x, y, 0.0f);
                GameObject newTile = Instantiate(TileSet[tileIndex], position, this.transform.rotation, this.transform);

            }
        }
    }

}

As you can see, the first tile is being positioned at a Vector3 of  0, 0, 0. The second at 0, 1, 0, and so on. At runtime this translates to Rect Transforms of 0, 0, -9720, and 108, 0, -9720 respectively.
Where is 108 coming from, and why is the Z an arbitrary -9720 when it should be a constant zero?
I suspect this must be due to canvas scaling, so I have attached an image of the canvas's settings.


texts: What were the typical price range for a development kit?

texts:
A lot of these things are usually behind NDAs and tricky to gauge. Is there any information and ranges on how much these thing costs?

For example, the PS1 had the "Net Yaroze", which according to Wikipedia was: "For about $750 USD, the Net Yaroze (DTL-H300x) package would contain a special black-colored debugging PlayStation unit with documentation, software, and no regional lockout."

So, what were the prices of some game development kits?

P.S: This might make a good community wiki


texts: Collision Detection/Map Management in RPG

texts:
I'm making an rpg game. I have a Grid class which takes a char[][] to create tiles. The way I'm currently doing collision detection is by creating a Player and assigning it the grid it should be created in.

However, (because it seems to be the easiest way to do things) I want to be able to have a class that has an array of Grids that only load the map information when neccessary (i.e. when the player is close enough to the next grid).

My past implementation was when i had a Grid[][]. However, this causes problems when I want to walk off my current grid and the game gives me a ArrayIndexOutOfBoundsException. My main concern is this: I want to be able to design a system that loads information as I need it.

My questions are: How should I go about doing this? Is this the most efficient way to design things? If I have to redesign something things, I'm willing to, as I'm in the early stages of game design.


texts:
I'm having trouble with isometric tiles drawing.

At the moment I got an array with the tiles i want to draw.
And it all works fine until i increase the size of the array.

Since I draw ALL tiles on the map it really affects the game performance (obviously) :D.

My problem is I'm no genius when it comes to javascript and I haven't managed to just draw what is in viewport.

Should be fairly simple for an expert though because its fixed sizes etc.
Canvas is 960x480 pixels, each tile 64x32.
This gives 16 tiles on first row, 15 on the next etc. for a total of 16 rows.

Tile 0,0 is in the top-right corner. And draws X up to down and Y right to left.
Going through the tiles on the first row from left to right as +X -Y.

Here is the relevant part of my drawMap()

function drawMap(){
    var tileW = 64; // Tile Width
    var tileH = 32; // Tile Height
    var mapX = 960-32;
    var mapY = -16;
    for(i=0;i<map.length;i++){
        for(j=0;j<map[i].length;j++){
            var drawTile = map[i][j];
            var drawObj = objectMap[i][j];
            var xpos = (i-j)*tileH + mapX;
            var ypos = (i+j)*tileH/2 + mapY; // Place the tiles isometric.
            ctx.drawImage(tileImg[drawTile],xpos,ypos);
            if(drawObj){
                ctx.drawImage(objectImg[drawObj-1],xpos,ypos-(objectImg[drawObj-    1]));
            }

        }
    }
}

Could anyone please help me how to translate this to just draw the relevant tiles?
It would be deeply appreciated.


texts: Finding out which tile a mouse click landed in

texts:
I am working on an isometric grid based game and im having an issue trying to link a mouse click from the user to a tile. I have been able to split the problem into 2 parts :

Finding a rectangle that surrounds a tile (which I have been able to do)
Figuring out from the rectangle which tile the click landed in (has got me stumped)

Here is an example of a rectangle with tiles on the inside:

The rectangle is 70px long and 30px high so if i use an input of say 30x(top)/20y(left)  how would I go about determining which tile this fell into?


texts: How to make a palette swap shader that works withn non-pixel art sprites?

texts:
I´m trying to build a tool inside Unity that allows our artists to create different color palettes for our characters.

The big problem is that since every single sprite is hand-drawn and hand-painted with different brushes there are no "traditional" color palettes defined for our base sprites. We use around 10-15 base colors for our characters but each character has tons of different shades and saturation variants to their base color on every frame (again, the art is brush-painted like).

Since color indexing is not really an option (unless I want to create a really big color index texture with a gazillion colors) I was wondering if there was a way to create a shader that, given a set of "base colors" and an equivalent color palette, swaps every "similar color" of the character with the color from the new palette (i.e. swap every single reddish color within a tolerance range with a newly defined color).

The goal here is to do this on a shader in real time. I could just write a script that does this and generates a new spritesheet with the swapped colors, but managing one spritesheet per character variation (we aim to have 10 variations per character) is really problematic for our workflow.

I really hope you can help me. I've been trying to find an answer for this for a week.


texts: How good do I have to be at Math to create a 3D game using three.js?

texts:
A question I've often had, how good at Math do I need to be to create 3 dimensional games? I get along with 2d games just fine. I understand everything I'm doing without problems after practise. However, jumping into 3d does seem a little scary and I'm worried my "bad at maths brain" will take it. I love creating games, I really don't want this to hold me back.

Is it possible to learn as I go along or do I need to have some natural math talent to be able to create 3d games? Also... if anyone can find a good place to start for a guy like me I'd really appreciate that too.

Thanks


texts: How often should I calculate the position of a bullet?

texts: In game's like Battlefield or Arma, how many times per second is the position of a bullet calculated?


texts: Why does the 3D window go blank on resuming from sleep/lock?

texts:
I have a 3d window hosted inside a WPF program.  This is written in C#, using SlimDX.  It uses a D3DImage subclass to support dx10 & dx11 rendertargets, like this site recommends: http://jmorrill.hjtcentral.com/Home/tabid/428/EntryId/437/Direct3D-10-11-Direct2D-in-WPF.aspx

However, when I resume from sleep, or even lock & unlock the screen on Windows, the 3D window goes blank until I resize it.  What is the appropriate way to mitigate this issue?

After resuming, but while the 3D window is still blank, I've confirmed:

The window ActualWidth & ActualHeight have not changed
The device is not null
The backbuffer is not null
The draw loop is still looping
The blank screen is occurring after the unlock. To prove this I put a Thread.Sleep() in the Unlock handling code to purposely lock the UI thread. The 3D image was still visible until the thread.sleep period ended, then it went blank.


texts: How to react properly to component field changes?

texts:
Let's say, that we have the following components:

Direction, which contains direction the object moves:

public class Direction : MonoBehaviour
{
    [SerializeField]
    private float angle = 0.0f;

    public float Angle
    {
        get
        {
            return angle;
        }
        set
        {
            angle = value;
        }
    }
}

DirectionVisualizer, which visualizes this direction in form of a sphere:

[RequireComponent(typeof(Direction))]
public class DirectionVisualization : MonoBehaviour
{
    private const float Radius = 2.0f;
    private GameObject sphere;

    private void PositionSphere()
    {
        Direction direction = GetComponent<Direction>();
        float angle = direction.Angle;

        Vector3 position = transform.position + new Vector3(
            Radius * Mathf.Sin(angle * Mathf.PI / 180.0f),
            0.0f,
            Radius * Mathf.Cos(angle * Mathf.PI / 180.0f));
        sphere.transform.position = position;
    }

    // Use this for initialization
    void Start () {
        sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        sphere.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);

        PositionSphere();
    }

    // Update is called once per frame
    void Update () {

    }
}

The relation above represents simplified model I'm having in my game - a component is used to visualize a set of parameters contained in other component(s).

Now I'd like the sphere to be automatically positioned basing on the angle field in Direction component without explicitly notifying DirectionVisualization, like:

var direction = someObj.GetComponent<Direction>();
direction.Angle = 25; // DirectionVisualization reacts automatically here

The simplest solution is to position sphere frame by frame, but I know, that Angle will change very infrequently and such solution would have dramatic impact on performance (in my game this visualization is a lot more complex).

I might do that by merging Direction and DirectionVisualization classes, such that I can handle Angle property setter, but that's a very ugly solution directly against SRR principle. So it's a no-go.

Other solution would be to create an event in Direction component and subscribe to it from within the DirectionVisualization component. But that raises following concerns:

If DirectionVisualization is destroyed, the event handler will keep it alive (I should probably detach the event handler when DirectionVisualization is destroyed?)
When DirectionVisualization is added to object, it should subscribe to Direction's event
What should happen if DirectionVisualization is added to object, which does not (yet) have Direction component? Is there a way to detect adding Direction component, such that DirectionVisualization might subscribe to the event?
What happens if Direction component is destroyed? How DirectionVisualization should behave? Is there way to detect it?

Is there a better way to handle notifications between components than one I proposed?


texts: "SetFloatImpl can only be called in the main thread." What does this mean and how can I fix this?

texts:
I am trying to create procedurally generated terrain and I have a Default texture with some code for my terrain material. An error pops up saying that SetFloatImpl can only be called in the main thread. What does this mean.

My default texture code is below:

    using UnityEngine;
using System.Collections;

[CreateAssetMenu()]
public class TextureData : UpdatableData {

    public Color[] baseColours;
    [Range(0,1)]
    public float[] baseStartHeights;

    float savedMinHeight;
    float savedMaxHeight;

    public void ApplyToMaterial(Material material) {

        material.SetInt ("baseColourCount", baseColours.Length);
        material.SetColorArray ("baseColours", baseColours);
        material.SetFloatArray ("baseStartHeights", baseStartHeights);

        UpdateMeshHeights (material, savedMinHeight, savedMaxHeight);
    }

    public void UpdateMeshHeights(Material material, float minHeight, float maxHeight) {
        savedMinHeight = minHeight;
        savedMaxHeight = maxHeight;

        material.SetFloat ("minHeight", minHeight);
        material.SetFloat ("maxHeight", maxHeight);
    }

}

the picture of the error is here:

Thanks in advance.

the complete message is here:

UnityException: SetFloatImpl can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
UnityEngine.Material.SetFloat (System.String name, System.Single value) (at /Users/builduser/buildslave/unity/build/Runtime/Export/Shaders/Shader.cs:492)
TextureData.UpdateMeshHeights (UnityEngine.Material material, System.Single minHeight, System.Single maxHeight) (at Assets/Scripts/Data/TextureData.cs:27)
MapGenerator.GenerateMapData (UnityEngine.Vector2 centre) (at Assets/Scripts/MapGenerator.cs:130)
MapGenerator.MapDataThread (UnityEngine.Vector2 centre, System.Action`1[T] callback) (at Assets/Scripts/MapGenerator.cs:73)
MapGenerator+<>c__DisplayClass16_0.<RequestMapData>b__0 () (at Assets/Scripts/MapGenerator.cs:66)
System.Threading.ThreadHelper.ThreadStart_Context (System.Object state) (at <437ba245d8404784b9fbab9b439ac908>:0)
System.Threading.ExecutionContext.RunInternal (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) (at <437ba245d8404784b9fbab9b439ac908>:0)
System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) (at <437ba245d8404784b9fbab9b439ac908>:0)
System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state) (at <437ba245d8404784b9fbab9b439ac908>:0)
System.Threading.ThreadHelper.ThreadStart () (at <437ba245d8404784b9fbab9b439ac908>:0)
UnityEngine.Material:SetFloat(String, Single)
TextureData:UpdateMeshHeights(Material, Single, Single) (at Assets/Scripts/Data/TextureData.cs:27)
MapGenerator:GenerateMapData(Vector2) (at Assets/Scripts/MapGenerator.cs:130)
MapGenerator:MapDataThread(Vector2, Action`1) (at Assets/Scripts/MapGenerator.cs:73)
<>c__DisplayClass16_0:<RequestMapData>b__0() (at Assets/Scripts/MapGenerator.cs:66)
System.Threading.ThreadHelper:ThreadStart()

I am using Sebastian Lagues' code for this.


texts: I am new to cocos2D development. Basically I want to develop game in which i want to move sprite forward with walking kind animation, must look real. Any help will be appreciated.


texts: Unity - Adding more functionality to a List Inspector

texts:
Let's say I have the following code:

public List<Armor> armors = new List<Armor> {
    new Armor() { name = "Black set",         folder = "black_set"},
    new Armor() { name = "Conquistador",      folder = "conquistador"},
    new Armor() { name = "Crusader",          folder = "crusader"},
    new Armor() { name = "Gothic Plate",      folder = "gothic_plate"},
    new Armor() { name = "K.D.",              folder = "kd"},
    new Armor() { name = "Lorica segmentata", folder = "lorica_segmentata"},
    new Armor() { name = "Rusty",             folder = "rusty"},
    new Armor() { name = "Spartan",           folder = "spartan"}
};

This appears in the editor like this:

While this is acceptable, there are a couple features I am missing: Lets take for instance the Sorting Layer list:

Here there are 2 features that I would like:

The ability to reorder elements on the editor
The ability to add more elements using + or -

Is there any way to add this functionality into my List?