# Question
Title: How can I add a new item to my enum list in the inspector?
I have a list of enums. I want to add a new item to it without scripting to make them more easily modifiable for game designers. I made an inventory system and I want to define the type of an item. For an example apple is a type of *food* and stone is a type of *object*.

Is there a way to group these items in the inspector?

```
using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
    public const string[] typesStrings = {"Player", "Prop", "Enemy"};
    [System.Serializable]
    public class TypeList
    {
        public enum types
        {
            PLAYER = 0,
            PROP = 1,
            ENEMY = 2
        }

    };

    // MonoBehaviour class
    public TypeList.types selectedType;

    public void Start()
    {
        string selected = TypeList.typesStrings[(int)selectedType];
    }
}

```

This, however, gives me the following error:

> Assets/grouping.cs(5,31): error CS0134: A constant `grouping.typesStrings' of reference type`string\[\]' can only be initialized with null

# Answer
> 6 votes
you can use System.Serializable

```
using UnityEngine;
using System.Collections;
public class grouping: MonoBehaviour {
    [System.Serializable]
    public class class1{
    public enum myEnum {one,two,three};
    public myEnum[] row;
    public string name;
    public int price;
    }
    public class1[] array;
}

```

useful link 1 for more information:

make your lists functional with ReorderableList

useful link 2 Custom Editors in Unity3D – Part 8: CustomEditor

Unity Editor: Enum Flags as Toggle Buttons useful link 3

---
Tags: c#, unity
---


title: Targeting logic for 100.000 units army

text:
# Question
Title: Targeting logic for 100.000 units army
I am making an army fight for my website armyfight. There can be fights of hundreds of thousands units. I am looking for better unit targeting. in jsfiddle is an example.

```
var enemy = {
    2: {
        3: {}  // object inside with unit data
    },
      5: {
        6: {}
    }
}

var ally = {
    4: {
        3: {}
    }
}

function unit_searches_for_target(y, x) {
    var closest_y   = iterate_Y(y);
    var unit_target = iterate_X(closest_y, x);
  return unit_target;
}

// Searches for closest target at Y axis
function iterate_Y(y) {
    if (_.has(target, y)) {
        return y;
    } else {
      var y = parseInt(y);
        for (var i = 1; i < 300; i++) {
            // If y == 4, it checks 4+1=5 (positive side)
            if (_.has(target, String(y + i))) {
                return (y+i);
            // Else if y == 4, it checks 4-1=3 (negative side)
            } else if (_.has(target, String(y - i))) {
                return (y-i);
            }
        }
    }
    // if didn't find anything, just returns same y as given
    return y;
};

// Searches for closest target at X axis
function iterate_X(y, x) {
    if (_.has(target[y], x)) {
        return {y: y, x: x};
    } else {
      var x = parseInt(x);
        for (var i = 1; i < 300; i++) {
            // If x == 4, it checks 4+1=5 (positive side)
            if (_.has(target[y], String(x + i))) {
            return {y: y, x: x + i};
            // Else if x == 4, it checks 4-1=3 (negative side)
            } else if (_.has(target[y], String(x - i))) {
              return {y: y, x: x - i};
            }
        }
    }
    // if didn't find anything, just returns same x as given
    return {y: y, x: x};
};

```

Here first i iterate on Y axis, later on X axis. But on different army positions it gives wrong results.
In this example, units are looking for targets by simply iterating. It is not very good for a huge army fight of hundred thousands units.
Best would be to iterate like here, when iteration process is much faster leading to first-hit success:

```
function iterate_X(y, x) {
  return _.find(enemy[y], function (value, key) { return parseInt(key) >= x });
}

```

But this iteration works only 0..100, or 99..100, but not 100..0, so i can't iterate objects in reverse mode.
So if ally is `{5: {10: {}, 99: {}}` and enemy is at `{5: {100: {}}}`, enemy unit would find closest ally as \[5, 10\] instead of \[5, 99\]. If it would be an array iterating backwards from 100 to 0, so it would be first-hit success. But can asotiative array be reverse-iterated?
Any suggestions please on structure? Maybe change units structure from objects to arrays or mix? But then I have problems with associative arrays. I am looking for an explanation or example about the structure and for a faster iteration for units targeting.
And i am also looking for websites, where i could ask these heavy logic questions? I have more of them.

# Answer
Organise your units in areas. An area can be a section in your grid (1

There are various implementations of quadtrees (Google is your friend).

This way a unit only has to iterate through the enemy units that are in neighboring quadtree spaces (or quadtree spaces within range of said unit).

This greatly speeds up the targetting/moving scenario's as each unit only has a subsection of the total number of units.

Once a unit moves, reorganise its position in the quadtree.
> 2 votes

---
Tags: collision-detection, javascript, architecture
---


# Question
Title: OpenGL(Libgdx) - How to texture a 2D terrain surface?
I want to texture the surface of my terrain.

I have created the ground mesh and surface mesh separately and everything is okay for ground mesh. But I couldn't texture the surface mesh correctly.

As below, the first one is what I want exactly and the second one is my output:

And my surface texture image looks like this:

My fragment shader:

```
#ifdef GL_ES
#define LOWP lowp
precision mediump float;
#else
#define LOWP
#endif

varying vec2 v_texCoords;
uniform sampler2D u_texture;

void main() {
  gl_FragColor = texture2D(u_texture, v_texCoords);
}

```

My vertex shader:

```
attribute vec4 a_position;
attribute vec2 a_texCoord0;
uniform mat4 u_projTrans;
varying vec2 v_texCoords;

void main() {
 v_texCoords = a_texCoord0;
 gl_Position =  u_projTrans * a_position;
}

```

Here is how I create my textures and draw my meshes:

```
   private void initializeTextures() {
        groundTexture = new Texture(Gdx.files.internal(Constants.SIMPLE_GROUND_FN));
        groundTexture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat);

        surfaceTexture = new Texture(Gdx.files.internal(Constants.SIMPLE_GROUND_SURFACE_FN));
        surfaceTexture.setWrap(Texture.TextureWrap.ClampToEdge, Texture.TextureWrap.Repeat);
        surfaceTexture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
    }

    public void draw(SpriteBatch batch){

        batch.setShader(shader);
        shapeRenderer.setProjectionMatrix(GameScreen.getCamera().combined);
        shader.begin();
        shader.setUniformMatrix("u_projTrans", GameScreen.getCamera().combined);
        groundTexture.bind(0);
        shader.setUniformi("u_texture", 0);
        groundMesh.render(shader, GL20.GL_TRIANGLES);
        surfaceTexture.bind(0);
        shader.setUniformi("u_texture", 0);
        shader.setUniformMatrix("u_projTrans", GameScreen.getCamera().combined);
        surfaceMesh.render(shader, GL20.GL_TRIANGLES);
        shader.end();

    }

```

And here is the method that generates mesh data:

```
public void createMeshes(int res) {
    Random r = new Random();
    int LENGTH = 15;
    //res (resolution) is the number of height-points
    //minimum is 2, which will result in a box (under each height-point there is another vertex)
    if (res < 2)
        res = 2;

    groundMesh = new Mesh(Mesh.VertexDataType.VertexArray, true, 2 * res, (2*res-1)*6,
            new VertexAttribute(VertexAttributes.Usage.Position, 2, "a_position"),
            new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoord0"));

    surfaceMesh = new Mesh(Mesh.VertexDataType.VertexArray, true, 2 * res, (2*res-1)*6,
            new VertexAttribute(VertexAttributes.Usage.Position, 2, "a_position"),
            new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoord0"));

    float x = 0f;     //current position to put vertices
    float med = 0.3f; //starting y
    float y = med;

    float slopeWidth = (float) (LENGTH / ((float) (res - 1)))/25; //horizontal distance between 2 heightpoints
    slopeWidth=0.1f;

    // VERTICES
    float[] tempVer = new float[2*2*2*res]; //hold vertices before setting them to the mesh
    float[] tempVerSurface = new float[2*2*2*res]; //hold vertices before setting them to the mesh
    int offset = 0; //offset to put it in tempVer
    int offset2 = 0;
    float[] tempVer2 = new float[2*res];
    int flahUp = 0;
    for (int i = 0; i<res; i++) {

        tempVer[offset+0] = x;      tempVer[offset+1] = 0; // below height
        tempVer[offset+2] = x;      tempVer[offset+3] = 0; // below height

        tempVer[offset+4] = x;      tempVer[offset+5] = y;  // height
        tempVer[offset+6] = x;      tempVer[offset+7] = y;  // height

        tempVerSurface[offset+0] = x;      tempVerSurface[offset+1] = y- .02f; // below height
        tempVerSurface[offset+2] = x;      tempVerSurface[offset+3] = y-0.02f; // below height

        tempVerSurface[offset+4] = x;      tempVerSurface[offset+5] = y+0.015f;  // height
        tempVerSurface[offset+6] = x;      tempVerSurface[offset+7] = y+0.015f;  // height

        //tempVer2[offset2+0] = x;      tempVer2[offset2+1] = 0f; // below height
        tempVer2[offset2+0] = x;      tempVer2[offset2+1] = y; // below height
        //next position:
        x += slopeWidth;
        if(flahUp < 20) {
            y += (r.nextFloat()*10)/200;
        }else {
            y -= (r.nextFloat()*6)/200;
        }
        flahUp++;
        if(flahUp > 35) flahUp = 0;

        offset +=8;
        offset2 +=2;
    }

    groundShape.createChain(tempVer2);
    groundMesh.setVertices(tempVer);
    surfaceMesh.setVertices(tempVerSurface);

    // INDICES
    short[] tempIn = new short[(2*res-1)*6];
    offset = 0;
    for (int i = 0; i<2*res-2; i+=2) {

        tempIn[offset + 0] = (short) (i);       // below height
        tempIn[offset + 1] = (short) (i + 2);   // below next height
        tempIn[offset + 2] = (short) (i + 1);   // height

        tempIn[offset + 3] = (short) (i + 1);   // height
        tempIn[offset + 4] = (short) (i + 2);   // below next height
        tempIn[offset + 5] = (short) (i + 3);   // next height

        offset+=6;
    }

    groundMesh.setIndices(tempIn);
    surfaceMesh.setIndices(tempIn);

    return;
}

```

So, maybe there is a very different way; this is actually my first game project and I don't know how to achieve this. What should I do to make my surface like the first one?

Thanks.

# Answer
> 3 votes
At least i have found the solution. It includes 2 step :

1- My surface texture wraping was wrong. X axis must be repeated and Y axis must be clamped to edges. The correct one is:

```
surfaceTexture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.ClampToEdge);

```

2- When we use "ClampToEdge" wrapping, texture's Y coordinates must be between 0 and 1. So i have changed texture coordinates that i put as parameter to surface mesh. The correct one is:

```
        tempVerSurface[offset+0] = x;      tempVerSurface[offset+1] = y- .02f;
        tempVerSurface[offset+2] = x;      tempVerSurface[offset+3] = 1f; // where i have changed

        tempVerSurface[offset+4] = x;      tempVerSurface[offset+5] = y+0.015f;
        tempVerSurface[offset+6] = x;      tempVerSurface[offset+7] = 0;  // where i have changed.

```

So at now, my surface texture is exactly as I want.

Thanks.

---
Tags: opengl, libgdx, textures
---


# Question
Title: Game Maker Studio - Check Collision With Subimages
I have an `obj_roulette`, which contains 4 subimages, with `value 2-5` and `image_number 0-3`. The value result from roulette stored as var `global.roulette`.

Then, I make many `obj_meteorite`, which contains 4 subimages too, spawn from above with `random x value` and `random image_number`. Player can shoot them with left-mouse click.

This is what I want:

`If image_number obj_roulette is 0, and player shoot obj_meteorite with image_number 0, score +10.
If image_number obj_roulette is 0, and player shoot obj_meteorite with image_number 1, score -10.`

I don't know how to check collision between `mouse_x/mouse_y` and object `image_number`, and how to match `obj_roulette` `image_number` and `obj_meteorite` `image_number`.

Is it using collision checking? If it yes, then maybe the example in this link can help: link 1

Please explain your answer. Thanks.

**update**

\[Simple Diagram Image\]

**update2**

Simple Diagram Image 2

# Answer
> 1 votes
**Yes**, it is collision checking. Though, there's a little misunderstanding about variables that I'll first try to clarify before proceeding to a solution to your problem.

### What does what

First of all, `image_number` is a constant (YoYo Docs call it *read-only variable*) that gives you the number of sub-images of an object's current sprite (its `sprite_index`). If you want information about the actual frame to be drawn in the current step, you need to check the instance variable `image_index`.

That's the story: `sprite_index` is the sprite assigned to an object to be drawn; `image_index` is the current sub-image (or frame) of its animation to be drawn in the next *Draw()* call; finally, `image_number` is the total number of sub-image of `sprite_index`. When you change an object's `sprite_index` its `image_number` value will be automatically updated by the GM engine.

So, let's work with `image_number`. This variable is usually set to -1, which means its value will be updated (so that the animation cycles through) depending on `image_speed` value. I'm assuming your `image_speed`s are already set to 0, so that you can set the value of `image_index`es without having them changing automatically over time.

### The first script

Now, to check mouse clicks onto objects depending on current `image_index`es, just add to the *Step Event* of `obj_meteorite` the following code:

```
// Check for an object being hit by the
// player: just a click, not continuously
if (mouse_check_button_pressed(mb_left))
{
    // Is the mouse above me while clicking?
    if (position_meeting(mouse_x,mouse_y,self))
    {
        // Was that the right object to hit?
        if (image_index==global.roulette)
            score += 10;    // Yeah
        else
            score -= 10;    // Nope
        // You may want to destroy the object
        instance_destroy();
    }
}

```

The function `collision_point()` belongs to the Advanced Collision Checking section in the YoYo Docs, as it's a more advanced way to check for instances whose collision masks include a particular point in the plane.

### Optimization

This script is executed by every `obj_meteorite` every time the left mouse button is pressed. That means, if there are currently 7 instances of `obj_meteorite` then this script will be called and executed seven times. But we have one mouse cursor only, so we would just check what lies below it. We can achieve this by migrating such script into a new object called `obj_controller`, which will execute a slightly different script in its *Step Event*:

```
// Check for an object being hit by the
// player: just a click, not continuously
var my_inst;    // Local support variable
if (mouse_check_button_pressed(mb_left))
{
    // Is there an instance below the mouse? Get its ID if yes
    my_inst = instance_position(mouse_x,mouse_y,obj_meteorite);
    // Is the mouse above the instance while clicking?
    if (my_inst!=noone)
    {
        // Was that the right object to hit?
        if (my_inst.image_index==global.roulette)
            score += 10;    // Yeah
        else
            score -= 10;    // Nope
        // You may want to destroy the object
        with (my_inst) instance_destroy();
    }
}

```

This way, the script is executed once only per mouse click. I guess your game isn't that complex and design optimization is no serious concern, but I suggest from time to time to check if your code can be designed and written differently to lower function calls and enhance your program performance, as it is good programming habit and practice.

---
Tags: collision-detection, mouse, game-maker
---


title: Shooting Projectiles

text:
# Question
Title: Shooting Projectiles
I am using cocos2D-x and am trying to achieve the effect of enemies going past and shooting projectiles at the player who is moving around the screen. I am using the code below, which is based on this article (Scroll down to the ’Shooting Projectiles’ section): https://www.raywenderlich.com/95835/cocos2d-x-tutorial-beginners

```
Point projPos = shooter->getPosition();
projectile->setPosition(projPos);
projectile->setVisible(true);

Vec2 offset = target->getPosition() - projPos;
offset.normalize();

auto shootAmt = offset * 1000;
auto projEndPt = shootAmt + projPos;

// Approach 1.
auto moveAct = MoveBy::create(10.0f, shootAmt);

// Approach 2.
auto moveAct = MoveTo::create(10.0f, projEndPt);

projectile->runAction(moveAct);

```

It works most of the time, however the projectiles speed varies, it seems based on the distance between the player and shooter. At medium distances the speed is fine, at shorter distances the speed is too slow and at longer distances the speed is too fast. The time being fixed (10.0f) over a variable distances seems to be the cause. I have tried both approaches as commented in the code, moving by move amount (Approach 1) and move to point (Approach 2) and both seem to give the same result.

# Answer
You are fixing the time to 10(seconds?), so it will always takke it 10 seconds to reach its target. So if its a short distance, the bullet will move very slow and over a long distance the bullet will move very fast. So you need to set the time to (distance)/(velocity).
> 1 votes

---
Tags: c++, 2d, vector, cocos2d-x
---


title: QuadTree nice design for nodes

text:
# Question
Title: QuadTree nice design for nodes
I'm using c++ and have some problems with the QuadTree design.

I have some components which are not related to the QuadTree directly. These components are eg. RenderableMesh, PointLight, etc. Some of them should be handled by a QuadTree and some of them should not.

I have a "reflection" system, so I can determine the type of a given component, that's not a problem.

A simple restriction is if I want to use a component in a QuadTree, it has to be inherited from the IBoundComponent which can be used to get the bounding box of the object (using a pure virtual function which is implemented in the exact Component)

This seems okay for me but for fast remove/insert operations of "changed components" (eg. the point light's radius is changed) I should store the current node/cell of the QuadTree. And here comes the real problem. Or actually problem**s**.

1)

Because the IBoundComponent does not know about the QuadTree directly, it has to have a public function pair which can be used to set/get the current node. I could use "friend class QuadTree" but that would restrict the spatial implementation to the QuadTree class.

2)

The Node class of the QuadTree is hidden (private). Of course I could store a void\* in the IBoundComponent and cast it. Or a base class (eg. ITreeNode) could be used and the QuadTree's Node should inherit from it.

Maybe a cleaner design would be the following:

Don't store anything in the IBoundComponent (expect the bounds...). When a component is changed, I could store the pre-update bounds as well as the post-update bounds. This way I can find which node contains the component and which will contain it. However this is an extra search. So it's a performance loss for cleaner design.

Do you have any good idea? I've searched here but cannot find a good answer for this situation.

# Answer
> 0 votes
My approach is that there is a `IQuadTreeItem` class that has a member `QuadTreeNode` to the parent node and a virtual method `ToBounding()` that returns the correct bounding container. I think the member variable is very clean and it provides nice and fast access for relocating and removing among other operations.

---
Tags: c++, quadtree
---


# Question
Title: capitalizing initial character in game maker studio
The value "V\_Output" is the string of letters that I wish to capitalize the initial of. The following code is run in the step event.

```
V_InitL=string_char_at(V_Output,1)
V_InitL_Cap=string_upper(V_InitL)

string_delete(V_Output,0,1)
string_insert(V_InitL_Cap,V_Output,1)

```

The resultant output as is produced in the draw event shows the original, un-capitalized version.

The following debug changes produce no detectable effect:

```
V_InitL=string_char_at(V_Output,1)
V_InitL_Cap=string_upper(V_InitL)

string_delete(V_Output,0,1)
string_insert("DEBUG",V_Output,1)

```

Why is this happening? What should I do to fix it?

# Answer
The following code fixed the problem:

```
V_InitL=string_char_at(V_Output,1)
V_InitL_Cap=string_upper(V_InitL)

V_Output=string_delete(V_Output,1,1)
V_Output=string_insert(V_InitL_Cap,V_Output,1)

```

As it turns out the effect of the last two functions can only be acquired if the variable has its value reassigned to the output of the functions (by adding "V\_Output=" in front)

Also, to delete single character, the index must be that of the target character.
> 0 votes

---
Tags: game-maker
---


# Question
Title: An invisible object that deletes anything behind it?
I am using augmented reality to put a 3D object on top of a "camera detected" object.

The 3D object can be though of as leaves that go above the real world object but also fall in front / behind / on the sides of it.

The leaves are not uniform so they appear as arcs which let more of the "camera detected" object be seen in some parts and less in others.

Because of this I want to only show the leaves that would normally be seen if there was a real 3D object (instead of the camera detected one) in that place. But since the camera detected one is just a background image part of the leaves on the side or behind are seen when the object is rotated.

I was thinking it might be possible to use an "invisible" object that moves and rotates the same way as the "camera detected" one so it behaves as a placeholder for depth testing but is not actually rendered.

Is this possible? May I have some pointers on how to achieve this?

Thank you

# Answer
Following Draco18s comment, I'm using a 3D object which is moved around the screen by tracking the live video object. Then I apply a depth mask to this object which behaves as if there was an actual object there since it allows my background to be seen wherever this object would be usually seen while still remaining invisible.
> 1 votes

---
Tags: unity, depth-buffer, culling
---


# Question
Title: Why doesn't this formula double the value properly?
Making a clicker game: Amount awarded per click not increasing based on how many increasers purchased.

I have a few global variables set up.

```
global.ramen_1 = 1

```

This part says how many ramen makers I have, or what my cursor level is, if you purchase another one it goes to 2, then 3 etc...

```
global.ramen_1_bonus = (global.ramen_1 * 2)

```

This is the formula that I want to work. If I own 10 ramen makers. Every time I click the ramen picture it is going to increase based on the value of global.ramen\_1 times by two. So in theory the more I buy, the higher it should go up when I click it.

I made the ramen image and clicking on it does the following code.

```
//Increases the amount of money by clicking the ramen
global.money += global.ramen_1_bonus

```

I have the object that you click that does this code which subtracts from the amount of money you have, but increases the amount of ramen makers you have. And for the time being I just have a static price, nothing that increases yet.

```
if (global.money >= 10) {
    global.money -= 10;
    global.ramen_1 += 1;
}

```

This works perfectly, ramen\_1 goes up by one, the money goes down by ten when you have enough.

BUT

After I have 2 ramen makers or `global.ramen_1 = 2`. The formula does not work.

When I click on the ramen bowl, my money doesn't go up 4 like it's supposed to, it still only goes up by two. Why not?

# Answer
I think that your issue relates to this formula:

```
global.ramen_1_bonus = (global.ramen_1 * 2)

```

This code is setting you bonus to twice global.ramen\_1.

If each time you click you increase global.ramen\_1 by 1 then you will increase your bonus by 2, that you are seeing.

From the sound of it you want to double the bonus so you would want something like:

```
global.ramen_1_bonus = (global.ramen_1_bonus * 2)

```

(After initialising it to 1 initially)

Or :

```
global.ramen_1_bonus = (2 ^ (global.ramen_1 - 1))

```

This is 2 to the power of (global.ramen\_1 - 1). I am uncertain about the specific gamemaker syntax. But either of those formulas should give you doubling of the bonus.
> 1 votes

# Answer
Where are you running `global.ramen_1_bonus = (global.ramen_1 * 2)`?

Perhaps you're not calling this line of code after updating global.ramen\_1?
> 0 votes

---
Tags: game-maker
---


# Question
Title: How to make expanding ring with constant thickness?
I need to generate this burst or (donut-shaped) pulse.
I'm having a difficult time how to generate such shape.
At first, I was thinking of scaling the image but that didnt work out because the line or "diameter" of the donut shape gets bigger accordingly..

https://www.youtube.com/watch?v=ewnEE5mt1ZM

# Answer
This code is adapted from a game demo in 'Cocos2d-x by Example Beginner's Guide' by Roger Engelbert.

```
circleSprite->setScale(0.1f);
circleSprite->runAction(ScaleTo::create(1.0f, 5.0f));

```

First it makes the sprite tiny (0.1f) and then runs an action to scale it up over 1.0 second (I have used an arbitrary scale to value of 5.0f for this example).

The circle sprite is just an image of a thick circle outline with the middle and outside transparent.

HTH
> -2 votes

---
Tags: c++, 2d, mathematics, cocos2d-x
---


title: TCG Board Architecture

text:
# Question
Title: TCG Board Architecture
While I was, sort of, studying the various TCGs around, concepts, similarities, differences and how they could be implemented, if designed to be in a virtual environment (e.g. PC game) I obviously noticed the most common element between them all: The Board

As a gaming developer community, you may know that The Board is where all the "action" takes place. It's similar to an MVC FrontController, handling everything of the game.

Programmatically speaking, several Observers would be implemented within it, to catch-up and interfere if needed in between every step taken by every card.

Most of them comes in a pyramid-a-like format like this:

```
              +------+
              |  12  |
              +------+

           //          \\

      +------+        +------+
      |  10  |   ==   |  11  |
      +------+        +------+

   //         \\   //        \\

+------+      +------+      +------+
|  07  |  ==  |  08  |  ==  |  09  |
+------+      +------+      +------+

   ||   \\   //   ||   \\   //  ||

-----------------------------------

+------+      +------+      +------+
|  01  |  ==  |  02  |  ==  |  03  |
+------+      +------+      +------+

   \\        //      \\       //

      +------+        +------+
      |  04  |   ==   |  05  |
      +------+        +------+

           \\          //

              +------+
              |  06  |
              +------+

```

This varies from game to game and can be 1x1, 3x3, 6x6, more or even less. This also can be like I designed above, vertically (which is easier to draw \>.\<), or horizontally, which I think is the best way for a programming implementation, specially considering a multi-platform goal.

In the diagram above, the lines and doubled equal signs represent possible interactions between cards, like, for example, supportive cards which sole objective in the game is to support (doh) adjacent cards somehow while disengaged ("not in combat").

Last but not least, cards may move between available spaces, be them on their own side (below/above the middle line) or in opponent's territory (the other half).

However, although I took notice of all these raw aspects, I couldn't find a way to make it work, again, programmatically speaking:

* **Should I use a multi-dimensional arrays or something better?**
* **How to identify that some space is free or occupied?**
    + **If occupied, how to identify if it is by a "team mate" card or opponent's**
    + **If it's free, how to find its neighborhood to identify possible "team mates" and targets**

I tried to hard-code a super structure with all possible attacker-opponent combinations, considering all possible targets for each attacker card on the front line group of 3 cards and also their adjacent supporters.

At the beginning of an hypothetical match of an hypothetical game (really), considering the cards as numbered above I came up to this, in a PHP array:

```
$board = [];

$board[ 1 ] = [ 't' => [ 7, 8 ],    's' => [ 2, 4 ] ];
$board[ 2 ] = [ 't' => [ 7, 8, 9 ], 's' => [ 1, 3, 4, 5 ] ];
$board[ 3 ] = [ 't' => [ 8, 9 ],    's' => [ 2, 5 ] ];

```

Each index of **$board** would represent a front line card with its possible targets under **t** and its supportive cards, if any, under **s**

Sounded good at first.

Then I simulated, all future possibilities if the first person, here named as the one on the lower half of the board, decided to make a move going to 1-7, 1-8, 2-7, 2-8 and so on and, after winning, automatically moving itself to the spot of its defeated opponent (which is mandatory in all TCGs I've seen to keep the board rotating).

This resulted in 7 different arrays:

```
// Active Player engages 1-7 and wins. Auto-move applied

$d1 = [];

$d1[ 8 ]  = [ 't' => [ 1, 2, 3 ], 's' => [ 9, 10, 11 ] ];
$d1[ 9 ]  = [ 't' => [ 2, 3 ],    's' => [ 8, 11 ] ];
$d1[ 10 ] = [ 't' => [ 1 ],       's' => [ 8, 11, 12 ] ];

// Active Player engages 1-8 and wins. Auto-move also applied

$d2 = [];

$d2[ 7 ]  = [ 't' => [ 1, 2 ],    's' => [ 10 ] ];
$d2[ 9 ]  = [ 't' => [ 1, 2, 3 ], 's' => [ 11 ] ];
$d2[ 10 ] = [ 't' => [ 1 ],       's' => [ 7, 11, 12 ] ];
$d2[ 11 ] = [ 't' => [ 1 ],       's' => [ 9, 10, 12 ] ];

// Active Player engages 2-7, wins. Auto-move also applied

$d3 = [];

$d3[ 8 ]  = [ 't' => [ 1, 2, 3 ], 's' => [ 9, 10, 11 ] ];
$d3[ 9 ]  = [ 't' => [ 3 ],       's' => [ 8, 11 ] ];
$d3[ 10 ] = [ 't' => [ 2 ],       's' => [ 8, 10, 11 ] ];

// Active Player engages 2-8 and wins. Auto-move also applied

$d4 = [];

$d4[ 7 ]  = [ 't' => [ 1, 2 ], 's' => [ 10 ] ];
$d4[ 9 ]  = [ 't' => [ 2, 3 ], 's' => [ 11 ] ];
$d4[ 10 ] = [ 't' => [ 2 ],    's' => [ 7, 11, 12 ] ];
$d4[ 11 ] = [ 't' => [ 2 ],    's' => [ 9, 10, 11, 12 ] ];

// Active Player engages 2-9 and wins. Auto-move also applied

$d5 = [];

$d5[ 7 ]  = [ 't' => [ 1, 2 ],    's' => [ 8, 10 ] ];
$d5[ 8 ]  = [ 't' => [ 1, 2, 3 ], 's' => [ 7, 10, 11 ] ];
$d5[ 11 ] = [ 't' => [ 2 ],       's' => [ 8, 10, 12 ] ];

// Active Player engages 3-8 and wins. Auto-move also applied

$d6 = [];

$d6[ 7 ]   = [ 't' => [ 1, 2, 3 ], 's' => [ 10 ] ];
$d6[ 9 ]   = [ 't' => [ 2, 3 ],    's' => [ 11 ] ];
$d6[ 10 ]  = [ 't' => [ 8 ],       's' => [ 7, 11, 12 ] ];
$d6[ 11 ]  = [ 't' => [ 8 ],       's' => [ 9, 10, 12 ] ];

// Active Player engages 3-9 and wins. Auto-move also applied

$d7 = [];

$d7[ 7 ]  = [ 't' => [ 1, 2 ],    's' => [ 8, 10 ] ];
$d7[ 8 ]  = [ 't' => [ 1, 2, 3 ], 's' => [ 7, 10, 11 ] ];
$d7[ 11 ] = [ 't' => [ 3 ],       's' => [ 8, 10, 12 ] ];

```

It grew a lot, but since all mathematical combinations that usually results in a moderate overload (specially for a web-based environment with PHP) was hard-coded, I didn't see a problem at first then and I kept going.

The next step was to consider all possible scenarios if the so called Active Player, now the former Opponent, in his own turn, decided to go in your first possible target **8-1**

Assuming a winning scenario, **8** could move itself to where **1** was or then **10** could be moved instead. It's mandatory, **at least** one card must always exchange positions when winning, otherwise the board doesn't rotate.

However, here comes the mathematically scary, although expected, part:

* If 8 Moves into 1, then:
    + 9, 10 or 11 *can* move over the previous location of 8, and then:
        - If 9 moves, 11 *can* move towards the former position of 9, and then:
            * If 11 moves, 10 or 12 *can* go to where 11 was, and then:
                + If 10 goes, 12 can jump to where 10 was
        - If 10 moves instead, 11 or 12 can move towards 10, In this case:
            * If 11 moves, 12 can go to 11
            * If 12 goes instead, 11 can be pulled back to 12
        - Now if 11 moves, then
            * 9, 10 or 12 can go to where 11 was, and then
                + If 9 goes, the flow stops
                + If 10 goes, 12 can go to 10
                + If 12 goes, 10 can pull back where 12 was

And here I stopped designing that data-structure mainly because this exponential grow wouldn't never reduce as far as other cards start leaving the fray, because in every "turn" several possible destination would still be available.

Their movement would still be restricted at once per turn, regardless the number of free spots, but still there are a lot of possibilities and I'm struggling to figure out a way to do make it viable.

All of this without mention cards I've seen in several TCGs with special abilities that allow them to jump more than one slot (usually the known as flying type). But this a future matter.

And by viable I kind of mean lightweight because, in order to explain here it obviously appears to be light, but in a real case scenario, each occupied space, for example, would store a object, with its own logic, dependency and thus, overload.

I thought about using a Binary Tree, but the nested "lower to left, higher to right" concept, at first, sounded not applicable. But I never used one before, so I might be wrong here.

I'd really appreciate some enlightenment.

# Answer
> 3 votes
*Card* and *Slot* concepts should not be mixed. They're not the same. My behind is not fused with the chair on which I'm sitting. This allows me to play musical chairs.

Let's organize your data:

```
// A card; belongs to a player, has abilities (among which we find 'CanJump')
Card
  Owner : Player // Blue or red
  CanJump : bool // Tells if the card can jump two slots

// A spot where a card can be on the board
Slot
  Neighbours : Slot[] // Immediate neighbours. Refer to slots on the board.
  JumpNeighbours : Slot[] // Slots that are 2 slots away and to which some card can jump
                          // Refer to slots on the board.
  Card : Card // Can be null; tells if there is a card there or not.

// Basically, a set of slots
Board
  Slots : Slot[] // All the slots on the board.

```

> Should I use a multi-dimensional arrays or something better?

No, use objects; the data structure is described above.

> How to identify that some space is free or occupied?

With the data above, this should be quite clear.

> If occupied, how to identify if it is by a "team mate" card or opponent's

Same.

> If it's free, how to find its neighbourhood to identify possible "team mates" and targets

Again, the answer is in the structure.

This structure allows for data driven design:

The following data will stay the same during the whole game session:

Slots on board definitions; define what slots exist

```
1
2
3
4
5
6
7
8
9
10
11
12

```

Slot Neighbours definitions; define which slots are direct neighbours

```
1 2
1 4
1 7
1 8
2 3
2 4
2 5
2 7
2 8
2 9
...

```

Slot Jump Neighbours definitions; define which slots have a 'jump' connection

```
1 3
1 6
....

```

Card definitions; describe what card exist and their features

```
Infantry     CannotJump
Magician     CanJump
ShieldBearer CannotJump
Lancer       CanJump
...

```

Now on a per-game session basis:

Slot card; the start definitions of the relations between a slot and a card, with the additional information; in this case, you need to tell to which player the card belongs.

```
1 Infantry     Player0
2 Magician     Player0
3 ShieldBearer Player0
4 ...
..
10 Lancer      Player1
11 ...

```

Your game code will update the slots in which the cards are 'placed'.

You can adjust the slots and the boards on your needs.

> How to identify the neighbor nodes?

```
Board.getSlots(2).getNeighbours()

```

# Answer
> 1 votes
I'm not 100% sure I caught your main idea between card relationships here, but to me it looks like some sort of network-like structure might work here. Your cards would have neighbours specified with some relation. It seems like you are trying to force a generic array here, but I think this is where using some traditional OOP simplifies the thinking process at least for me.

```
class Node
{
    Node neighbours[];

    Card card;
}

```

This separates the actual cards from the possible card positions. For swapping cards, you could then just easily swap the assigned cards of the required nodes. You might want to store a reference to each card's parent node in the card implementation, but that depends on the way you want the interface to work.

---
Tags: architecture, php
---


# Question
Title: Develop a Wii U game without official dev kit
I was looking for unity for Wii U game development. But it seems that I need the approval of Nintendo to have the software (and special hardware) (ref: https://wiiu-developers.nintendo.com).

Is there a way to have the software and to replace the hard with an emulator ?

I just want to make a game for fun, I can't afford the official SDK (Rumors says it about $5000)

If it is possible, I would love to have some ressources (I couldn't find anything...)

Thanks :-)

# Answer
> 6 votes
This is a question best answered by Nintendo themselves. I have a suspicion that Nintendo isn't interested in people making games just for fun, since it can potentially hurt the Nintendo trademark. They want the name Nintendo be associated with quality, or seemingly quality.

# Answer
> 1 votes
Just to mention:

Since I posted this question, I went on the official website to register as an "official" developer.

I could get their approval in less than a month.

I think the commercial situation of the WiiU is so bad that they are ready to let anyone try to make great games.

But I still need to buy or rent dev material which is a bit expensive for non professionnal (I am not allowed to disclose the price, sorry)

---
Tags: unity, wii
---


# Question
Title: Unity 5: Use Network Simulator, should I?
I am looking to test intelligent prioritisation of a client server game. In my scenario, two clients are connected to the server. I want one client to have a good connection to the server while the others is poor. With my test environment the server and clients are machines within a lab. Can the network simulator within the Network Manager Script do this? Can the network simulator be used on the clients or does it have to be used on the server? Can I, for my situation, have one client use it and bump up the latency or packet loss and then have the other client not use it? I couldn't find anything within Unity's Documentation about this.

# Answer
For anyone looking for good network simulation software go here https://jagt.github.io/clumsy/ Clumsy doesnt need installed or anything, just run it and specify your parameters. I realise it is really simple but it is what I needed. Hopefully this helps.
> 3 votes

---
Tags: networking, unity, unity-networking
---


# Question
Title: How Do I Play An Animation In Unity 5.3.4?
I am confused on how to play an animation with the new unity version because the flag "Automatically Play Animation" is gone. I cant have the animation connected to my GameObject because it plays right away.

```
using UnityEngine;
using System.Collections;

public class FPSCamera : MonoBehaviour {

    public float lookSensitivity = 5;
    private float xRotation;
    private float yRotation;
    private float currentRotationX;
    private AnimationClip walking;

    void Start() {
        // DONT KNOW HOW TO FIND AND START WALKING ANIMATION CLIP
    }
    void Update() {
        yRotation += Input.GetAxis("Mouse X") * lookSensitivity;
        xRotation -= Input.GetAxis("Mouse Y") * lookSensitivity;
        xRotation = Mathf.Clamp(xRotation, -90, 90);
        transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
    }
}

```

# Answer
You need to set up states in the animator panel. You can open it by double clicking on a animation controller. To create a animation controller just drag the animation Clip onto the gameObject you want. Once you have the animator panel opened you need to create a parameter to handle the transitions. Here is a picture of a example Animator set up.  Then you use a script that looks something like this to set the transition.

```
public class NewBehaviourScript : MonoBehaviour {
    private Animator animator;
    // Use this for initialization
    void Start () {
        animator = GetComponent<Animator>();
        animator.SetBool("startWalking", true);
    }

    // Update is called once per frame

}

```
> 1 votes

---
Tags: unity, animation
---


title: Drawing bullets on a map

text:
# Question
Title: Drawing bullets on a map
I'm going to be making a shooter-style game, on a navigatable map (All 2D). I'm a little unsure of how to handle the bullets: I see two main ways i could do it

I could have the bullet's x and y position be updated based on its trajectory, and then draw it using the formula

Screen.x - Bullet.x , Screen.y - bullet.y

This would draw the bullet relative to the players location, so that it would appear on the map

The other main method I am considering is drawing the bullet directly to the map image via the getGraphics() method. However, this seems like it could cause performance issues, as just testing this seemed to lag

(this was my test method)

```
public void Draw(Graphics g){
    image.getGraphics().drawRect(10,10,10,10);
    g.drawImage(image,0,0,null);
}

```

Adding in the drawRect line caused considerable lag - removing it made the game run fine

Are either of these a good way to handle drawing projectiles? If not, how else could I do it efficiently?

# Answer
It would appear your rendering logic is completely flawed. Take a look at this question and it's answers, you appear to be doing some of the same errors I previously did.

Canvas - good rendering practices?

**About Projectiles**

Drawing one rectangle will literally never have any noticeable impact on your frames so there is obviously a flaw elsewhere, hopefully the above link will help you address that. Here's a basic run down on how you could implement your project system:

1. First off, make yourself a class that can be the base class for all objects in your game... Let's call it... `GameObject` !
2. `GameObject` is an `abstract` class and will have 2 methods that will be overwritten by classes which extend it.
3. Next, create an object for your bullet, we can call it `Bullet`, this class wil `extend GameObject`.
4. Now going back to your`GameObject` class, add 2 abstract methods:

`public abstract void update();`

`public abstract void render(Graphics2D g);`
5. Your `GameObject` class should also have 2 fields for holding the it's x and y positions respectively.
6. Implement your abstract methods in your `Bullet` class and add your `drawRect` code. It should look something like this:

```
public void render(Graphics2D g){
    g.drawRect(x, y, 5, 5);
}

```
7. Now you need a class to keep track of everything that exists in your game world. I usually name it `Level` or `World`. This will contain a `List` of all your `GameObject`s. Now in your main game loop simply go through all of the GameObjects stored in your world and update them, then run through again and render them all.

---

**Rendering with camera offsets**

When rendering a game world that's larger than the players window (Be it a monitor, JFrame, Canvas) you will want to be able to add an offset to the world being rendered, this can be achieved with an imaginary "camera".

I say imaginary because the camera doesn't quite work as you'd expect. Instead of the camera looking at a certain part of the world, the world instead translates itself to be within the frame of our camera! So let's say we have a `Screen` class with variables `xScroll` and `yScroll`.

Every time something is rendered we must subtract these two variables from the rendered location. This can be achieved in two ways:

**Method 1: Encapsulate your Graphics2D Object With your Screen**

This is my preferred method, it requires a bit of extra work on your part but makes the entire rendering system far far simpler. So as of now our abstract class `GameObject` has a `render(Graphics2D g)` method. We're going to change this to `render(Screen screen)`, this new `Screen` class will keep a reference to a `Graphics2D` object and will have some methods that are the same as the underlying `Graphics2D` object with one addition, they will subtract the `Screen`'s `xScroll` and `yScroll`. Example:

```
public void drawRect(int x, int y, int width, int height){
    g.drawRect(x-xScroll, y-yScroll, width, height);
}

```

After this you need only implement appropriate methods into your `Screen` class for whatever methods you want to encapsulate out of `Graphics2D`. Finally, update the two scroll variables in your main game loop to easily center the camera on your player.

**Method 2: Simply subtract it in your render method**

So this method is simpler but also doesn't respect Reuse or Encapsulation design patterns. But is great for just a simple game like yours.

Just simply add `static` variables `xScroll` and `yScroll` to your `Screen` class and subtract these in your `Bullet`'s (and any other `GameObject`s you decide to add) render method. Example:

```
public void render(Graphics2D g){
    g.drawRect(x-Screen.xScroll, y-Screen.yScroll, 5, 5);
}

```

I hope this addresses all your problems :<sup>)</sup>
> 1 votes

---
Tags: java, performance
---


title: glGenBuffers is NULL

text:
# Question
Title: glGenBuffers is NULL
I'm using GLEW 1.13.0, (GLUT), SDL2 and OpenGL 3.3 core.

```
#include <GL/glew.h>
#include <GL/glut.h>

int main(int argc, char* args[]){
  Engine::init(); // Initializes SDL_GL_* attributes

  glutInit(&argc, args); // Don't know if needed
  glewExperimental = GL_TRUE;
  glewInit();

  WINDOW["main"] = new Window("Test", {800, 600}, false, true);

  GLfloat vertices[] ={
    -0.5f, -0.5f, 0.0f,
    0.5f, -0.5f, 0.0f,
    0.0f, 0.5f, 0.0f
  };
  GLuint VBO[1];
  glGenBuffers(1, VBO); // Here my program crashes as glGenBuffers is NULL
  glBindBuffer(GL_ARRAY_BUFFER, VBO[0]);
  glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

  ...
}

```

# Answer
As far as I know, you must initialize GLEW *after* creating GL context. Which means, after creating a window.

---

If it wont work, please post an entire code of `Engine::init()`.
> 2 votes

---
Tags: opengl, sdl2
---


# Question
Title: How to remove white background from an image using LibGdx?
I am fairly new to game development.

I am developing an application(Aquarium) for windows which requires me to animate(move) fishes around the screen and user will be able to add new fishes drawn on paper and scanned into the application, I did some research and decided to use LibGDX so when user scans the image coming to the system has White background which needs to be removed I needed to know how to remove that make it transparent in LibGDX.

# Answer
> 1 votes
It seems like you are asking more about image processing and not LibGDX specifically. Once you change the white background to transparent pixels, then LibGDX will draw it without the transparent pixels.

The algorithm that you are looking for is called Background subtraction or Foreground detection. I have had some success before (albeit in Android) with OpenCV and I believe that you should be able to get the library working on Desktop within Libgdx. It is open source and free to use commercially.

OpenCV has a Java interface and it has a function called `grabcut()` that does Background subtraction. It is a bit more accurate if you have your user give hints for which pixels are foreground.

Here is another SO post that may help you get OpenCV working

---
Tags: libgdx, filtering
---


title: How Do I Play An AnimationClip

text:
# Question
Title: How Do I Play An AnimationClip
I want to play an animation but it seems that in The new version of unity it is harder. I have an AnimationClip but I don't know how to play it. I have been looking at this for 2 hrs now and i cant get it to work.

```
using UnityEngine;
using System.Collections;

public class FPSCamera : MonoBehaviour {

public float lookSensitivity = 5;
private float xRotation;
private float yRotation;
private float currentRotationX;
private Animation walking;

void Start() {
    // DONT KNOW HOW TO FIND AND START WALKING ANIMATION
}
void Update() {
    yRotation += Input.GetAxis("Mouse X") * lookSensitivity;
    xRotation -= Input.GetAxis("Mouse Y") * lookSensitivity;
    xRotation = Mathf.Clamp(xRotation, -90, 90);
    transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
}
}

```

# Answer
> 1 votes
In order to play an animation there needs to be an Animation Component attached to your GameObject. In that animation component you can add the animations you wish to play. If you don't want the animation to play on start make sure you un-check "Play Automatically". If you want to add more animations click the "Animations" drop down and set the "Size" to the amount of animations you wish to add.

When you want to access and play those animations you reference the Animation Component and use the "Play" method like so:

```
private Animation myAnimationComponent;

private void Start ()
{
    myAnimationComponent = GetComponent<Animation> ();
    myAnimationComponent.Play ("nameOfDesiredAnimation");
}

```

Unless you only have a few animations that you want to play at specified times, an Animator Controller would be a better option in most cases. In your case it looks like you want to animate a character; I would highly suggest using an Animator Controller instead of the Animation Component.

Let me know if you have any questions or suggestions.

---
Tags: unity, animation
---


# Question
Title: What technique would I use to animate a 2D curling tentacle?
I have played around in Cocos2D-X and I think I understand the limitations of sprite-based animation fairly well.

I want to have a game with some characters curling and extending a tentacle which varies in length and amount of curl depending on the terrain.

Maybe imagine a sloth swinging from a tree but with arms that stretch at times (Gumby character?).

Is there a name for such a technique?

Would this be a variant on Animating Bezier Curves as seen in Jason Davies's example or discussed in this blog on tweening control points?

I'm a very experienced polyglot programmer but relatively naive in games and graphics.

# Answer
Since you're referring to s 2D sprite based game, I would use sprite segments to create the tentacle.

Each section inherits the rotation angle from the parent and adds a bit of angle of it's own. Each section *n* is calculated as

```
section[n].position.X=section[n-1].position.X+cos(section[n-1].angle)*sectionlength;
section[n].position.Y=section[n-1].position.Y+sin(section[n-1].angle)*sectionlength;
section[n].angle=section[n-1].angle+extraangle;

```

Now by altering the angle for each section you can make the tentacle curl. Add sections or stretch the section length (scale the sprites) you can vary the lentgh of the tentacle.
> 3 votes

# Answer
It seems that Soft Body Physics comes close, particularly as seen in Skeel Lee's work with goal and surface springs and Pressurized Soft Body with Local Deformation.

Note I found the above following the answers on Dynamic body implementation
> 0 votes

# Answer
Based on @felsir's answer, yes it looks like Spine is probably the answer. A graphical modelling tool, it includes exports to a number of game engines.

Relevant technologies it includes, which gives me the bibliography I was searching for, are:

* Free-form deformation so a model defined in a mesh can be distorted, combined with Weights (aka Skinning) to attach images to the mesh.
* Inverse Kinematics to help work backwards from the range of motion desired, to define joints needed
> 0 votes

---
Tags: animation
---


# Question
Title: How to fill a canvas with triangles that are seemingly random?
Given a canvas say, 1000 X 1000 unit. I would like to fill the canvas with triangles. The triangles can be of any type right angle, equilateral...etc. To avoid big chunks of triangles lets say all triangles should be of some area say, 40 unit^2. Any suggestions will be appreciated, thank you.

I'm trying to draw something like this:

# Answer
> 1 votes
1. Add some random points
2. Repell points located too close to each other
3. Add some points along the edges
4. Do Delaunay Triangulation on all the points
5. Done

---
Tags: 2d, algorithm, graphics, html-canvas
---


title: Detect Collision on Child Object

text:
# Question
Title: Detect Collision on Child Object
I've created an obstacle prefab. The Prefab has following hierarchy.

The player must die if he collides with Enemy. But It detects collision with parent object. I am also uploading the screen shot of property of enemy(Child Object) and Parent Object.

What should I change to let player collide with Child Object (Enemy).

# Answer
The box collider on the parent object is marked as "is Trigger". Maybe your code for the collision detection for this collider is causing the player to die when colliding with the parent object.
> 1 votes

---
Tags: unity, collision-detection
---


title: Making Basic Touch Behaviors

text:
# Question
Title: Making Basic Touch Behaviors
I am trying to make Basic Touch behaviors for my game where i want to

1. Pan Camera by Single finger touch.
2. Zoom Camera by pinch With two fingers ofCourse.
3. Rotate Camera by two fingers rotation.
4. Rotate camera around an object and move only in x axis using Two fingers y position.

i am having problem in making camera to rotate on X axis but i am not able to do it correctly plz help and it also conflicts with my pan behaviour when input is given

```
   public float comfortZoneVerticalSwipe_A = 10;
    public float comfortZoneHorizontalSwipe = 50;
    public float minSwipeDistance = 100;

    public float startTime;
    public Vector2 startPos;
    public float maxSwipeTime = 0.5f;

    if (Input.touchCount > 0 && Input.touchCount < 2)
            {
                Touch touch = Input.touches[0];
                switch (touch.phase)
                { //following are 2 cases

                    case TouchPhase.Began: //here begins the 1st case
                        startPos = touch.position;
                        startTime = Time.time;

                        break; //here ends the 1st case

                    case TouchPhase.Moved:

           Vector3 offset = transform.right * (-Input.touches[0].deltaPosition.x * 0.9f) * panSpeed + transform.up * (-Input.touches[0].deltaPosition.y * 0.9f) * panSpeed;
                                Vector3 newTargetOffset = Vector3.ClampMagnitude(offset, maxOffsetDistance);

                                transform.position += newTargetOffset - targetOffset;

                        break;

                    case TouchPhase.Ended: //here begins the 2nd case

                         float swipeTime = Time.time - startTime;
                        float swipeDist = (touch.position - startPos).magnitude;

                              Debug.Log("Mathf.Abs(touch.position.x - startPos.x) " + Mathf.Abs(touch.position.x - startPos.x));

                            Debug.Log("swipe Time " + swipeTime);

                            Debug.Log("swipe Dist " + swipeDist);

                            if (Mathf.Abs(touch.position.x - startPos.x) < comfortZoneVerticalSwipe_A && swipeTime < maxSwipeTime && swipeDist > minSwipeDistance && Mathf.Sign(touch.position.y - startPos.y) > 0)
                        {

                            Debug.LogWarning(transform.rotation.x);
                            transform.rotation = new Quaternion(transform.rotation.x - 5 , transform.rotation.y , transform.rotation.z , transform.rotation.w);
                           if (transform.rotation.x > 0.2)
                           {
                                transform.Rotate(Vector3.right, -2);
                            }
                                Debug.LogError(transform.rotation.x);
                            Debug.LogWarning("Up");

                        }
                            else if (Mathf.Abs(touch.position.x - startPos.x) > comfortZoneVerticalSwipe_A && swipeTime > maxSwipeTime && swipeDist > minSwipeDistance && Mathf.Sign(touch.position.y - startPos.y) < 0)
                            {

                                 transform.rotation = new Quaternion(transform.rotation.x - 5 , transform.rotation.y , transform.rotation.z , transform.rotation.w);
                                if (transform.rotation.x < 0.9)
                                {
                                    transform.Rotate(Vector3.right, 2);
                                }
                                print("down");

                            }

                        break; //here ends the 2nd case
                }
            }

```

# Answer
Why are you changing the position of the camera using `transform.position += newTargetOffset - targetOffset;` ?

While panning, you should only rotate the camera. Also, what is `targetOffset`?
> -1 votes

---
Tags: c#, unity, touch
---


# Question
Title: How to move 2D objects based on mouse movement with pointer locking?
I'm using pointer locking for a 2D game (where you perform calculations based on the delta in mouse positions from frame to frame). I'm having some basic math/logic issues with accomplishing what I want.

I'd like the player to be able to send the character in the direction they last moved their mouse (so if they stop moving the mouse, the character continues to travel in the direction they last moved in).

The issue I'm experiencing is the movementx and movementy values are integers. If the player moves the mouse quickly so that from one mousemove event to the next many pixels are traversed, the direction to move the character is reasonably precise. Every other scenario results in the last movement having movementx or movementy only being -1/0/+1. If the character only moves based on the last movement of the mouse, it very often only moves in one of 8 directions.

**How can I be more precise than 8 directions even on slow/short mouse movements while ensuring the last bit of movement of the mouse is always what's being used?**

My first thought was to average out the last n movement values, but that can easily result in the character not always moving in the direction the mouse moved last. I've not really had too many other thoughts though, so I came here for assistance.

# Answer
The whole setup seems a bit strange.

Is the speed always a fixed number, and what you're dealing with now is how to choose direction? Or is the speed dependent on the movement as well?

If the latter case (speed dependent on mouse movement): You should either make this "physical", i.e let the delta mouse movement result in acceleration, or link delta position to delta mouse, and just stop it when mouse stopped moving (i e skip your idea).

If the first case (fixed speed): As I said, I find this user interface really strange, and I think your problem is manifestation of that.

Either way - you've encountered a common problem where you estimate angle from a short distance (it's even more evident that there is a problem if you consider the "singularity" when delta = 0).

Perhaps an easy way out would be to choose the last value where the magnitude is larger than some fixed value?
> 0 votes

---
Tags: physics, mathematics, javascript, mouse, logic
---


# Question
Title: Are there official button images for the xbox controller that I can get for free?
If you want to support xbox controllers, it is always wise to use the native images that the controller uses. Can one obtain those from Microsoft without being a registered, aka paying developer?

# Answer
> 5 votes
You can get official Microsoft logos here: http://www.microsoft.com/en-us/news/ImageGallery/logos/logoguidelines.aspx (You have to agree to their terms in order to get to the logo part).

Here you might get some publicly available assets: http://www.microsoft.com/en-us/news/imagegallery/products/default.aspx (Well, there isn't a top-down shot of X-Box controller, but maybe you can get away with Limited Edition one)

So, to directly answer your question - **no**, there are not publicly available official images to be used for keymapping hints.

Last, but not least, you can always try to look up contacts of the company, and send them an email. You're not asking for a free X-Box, Kinect, TV and sofa - it's only an image.

I, personally, am not a developer of X-Box games or anything related to X-Box, but maybe you get some illustrations with the developer kit?

# Answer
> 4 votes
There is an unofficial but extremely complete set of controller button images for several platforms here:

http://opengameart.org/content/free-keyboard-and-controllers-prompts-pack

# Answer
> 0 votes
These are not official, but are good...

http://sinnix.net/downloads/

---
Tags: art, pc, xbox-controller
---


# Question
Title: LIBGDX: Translate grid drawn with ShapeRenderer with an OrthographicCamera
I am trying to draw a grid for my "world" that may or may not extend beyond the screen. What I would like to do right now is draw the entire world (which is relatively small) and then use the orthographic camera to translate the view to where the player is inside the "world." Currently I'm just trying to translate the "world" by 100 on the x and y axis to test. What am I doing wrong? Can I use the Shaperenderer with the OrthographicCamera?

```
public class WorldRenderer implements Disposable{

    private static WorldRenderer worldRenderer;
    private Color gridLineColor = Color.LIGHT_GRAY;
    private OrthographicCamera camera;

    private int worldX;
    private int worldY;

    public WorldRenderer(WorldController worldController) {

        init();

    }

    public void init() {

        worldRenderer = this;
        camera = new OrthographicCamera();

        worldX = 0;
        worldY = 0;

    }

    public void render() {

        //Set the background color to white.
        Gdx.gl.glClearColor(255, 255, 255, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        renderBackground();

    }

    public void renderBackground() {

        ShapeRenderer renderer = new ShapeRenderer();

        //Draw vertical lines.
        for(int i=0;i<=Constants.WORLD_WIDTH * Constants.GRID_WIDTH;i+=Constants.GRID_WIDTH) {

            renderer.begin(ShapeType.Line);
            renderer.setColor(gridLineColor);
            renderer.line(i, 0, i, Constants.WINDOW_HEIGHT);
            renderer.end();

        }

        //Draw horizontal lines.
        for(int i=0;i<=Constants.WORLD_HEIGHT *          Constants.GRID_HEIGHT;i+=Constants.GRID_HEIGHT) {

            renderer.begin(ShapeType.Line);
            renderer.setColor(gridLineColor);
            renderer.line(0, i, Constants.WINDOW_WIDTH, i);
            renderer.end();

        }

        camera.translate(100, 100);

    }

}

```

# Answer
> 0 votes
Whenever you modify a camera's position, you need to call `camera.update()` so that it will update all of the other variables that the camera uses. This update call should be done before any drawing is done. In my games, I usually call camera.update() at the beginning of my render function.

Second, it looks like you are calling `camera.translate(100,100)` every frame. The will move your camera very quickly outsize your map bounds. Perhaps you meant to do this initial translation in the `init()` method.

Lastly, the `ShapeRenderer` has it's own drawing matrices and knows nothing about the camera position. You need to tell it every time the camera changes.

```
camera.update();
shapeRenderer.setProjectionMatrix(camera.combined);

```

---
Tags: java, libgdx, graphics
---


title: Removing delay at start of a key press

text:
# Question
Title: Removing delay at start of a key press
I'm making a simple game, and one of the problems I encountered is the annoying delay when pressing a key continuously.

So basically, when I press (for a very long time) for example `Up`, my object will move 1 unit up, not move (for approx. 1 second), and then move continuously 1 unit up (without any delays).

Currently, I use this to move the object (SDL2):

```
while (SDL_PollEvent(&event))
{
    switch (event.type)
    {
    case SDL_KEYDOWN:
        switch (event.key.keysym.sym)
        {
        case SDLK_UP:
            //Move object 1 unit up
            break;
        //Other unrelated things omitted
        }
        break;
    //Omitted other cases
    }
}

```

What I would like to have is to remove the delay, so that the object can immediately move `Up` very quickly. Is there any way to do this?

# Answer
> 17 votes
By waiting for key-down events to be fired, you are likely at the mercy of the key event repeat rate that the OS controls (and which users can specify themselves).

Instead, you may want to call `SDL_GetKeyboardState` at the top of your game update loop (the part of the update that happens *every* frame, whether or not an event has come in) to get the state of the keyboard and check that to see if the up key is down or not during any individual frame.

# Answer
> 10 votes
An alternative way (Josh's approach is great too!) would be to setup an boolean on `SDL_KEYDOWN`, and possibly also ignoring all repeated key events. That you can do by checking the `repeat` member of the key event.

Then you could implement your own timer, which doesn't have to be anything fancy, and implement key repetition your self. You could either trigger the action directly from the timer, or even generate an `SDL_KEYDOWN` event, and unify the solutions.

---
Tags: c++, sdl2, keyboard
---


title: Top Down Bullets will not move

text:
# Question
Title: Top Down Bullets will not move
I have a top down shooter. The player can move in the primary 4 directions, and follows the mouse for rotation.

When I shoot, the bullets never leave the player, they just spawn on top of the player sprite.

I have tried a combination of velocity and AddForce methods, but I don't understand why the bullets never move. I have tried moving them in the Bullet's script or in the calling WeaponAttack script that Instantiates the Bullet.

***Side note for educational purposes***: Which method is better? Should the bullet govern its direction and velocity or should the Instantiating class govern it?

**PLAYER ROTATION SCRIPT**

```
public class RotateToDirection : MonoBehaviour {

    Vector3 mousePos;
    Camera cam;
    Rigidbody2D rid;

    void Awake () {
        rid = this.GetComponent <Rigidbody2D> ();
        cam = Camera.main;
    }

    void FixedUpdate () {
        rotateToDirection ();
    }

    private void rotateToDirection() {
        mousePos = cam.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z - cam.transform.position.z));
        rid.transform.eulerAngles = new Vector3 (0, 0, Mathf.Atan2 ((mousePos.y - transform.position.y), (mousePos.x - transform.position.x)) * Mathf.Rad2Deg);
    }
}

```

**WEAPONATTACK (SHOOTS THE BULLET)**

```
public class WeaponAttack : MonoBehaviour {
    public GameObject bullet;
    public GameObject player;

    public float bulletSpeed;

    void FixedUpdate () {
        if(Input.GetMouseButton (0)){
            attack ();
        }

    }

    public void attack(){
        Instantiate (bullet, player.transform.position, player.transform.rotation );
        //Rigidbody2D bulletInstance = Instantiate(bullet, transform.position, Quaternion.Euler(new Vector3(0, 0, 1))) as Rigidbody2D;
        //bulletInstance.velocity = transform.forward * bulletSpeed;

        Physics2D.IgnoreCollision(bullet.GetComponent<Collider2D>(),  player.GetComponent<Collider2D>());

    }

}

```

**BULLET**

```
public class Bullet : MonoBehaviour {

    public float moveSpeed = 500.0f;
    private float killTime = 1.0f;
    private Rigidbody2D body;

    void Awake() {
        body = GetComponent<Rigidbody2D> ();
    }

    void FixedUpdate(){
        killTime -= Time.deltaTime;
        if (killTime <= 0) {
            Destroy (this.gameObject);
        } else {
            body.position = body.position * moveSpeed * Time.deltaTime;
        }
    }

}

```

# Answer
> -1 votes
```
    GameObject bulletInstance = Instantiate(bullet, transform.position, player.transform.rotation) as GameObject;
    bulletInstance.GetComponent<Rigidbody2D> ().velocity = transform.right * bulletSpeed;

```

---
Tags: unity, c#, 2d, monodevelop
---


# Question
Title: Why is my custom shader rendering completely transparent?
I'm currently trying to learn how to write shaders, so I'm getting my feet wet with Unity's Shaderlab format. One of the first things I tried was to write a surface shader that supports vertex colors being assigned from code. Unfortunately, whenever I try to apply the shader to my object, it just renders the object completely transparent.

```
Shader "Custom/SVCA" {
    Properties {
        _Color ("Color", Color) = (1, 1, 1, 1)
        _MainTex ("Base (RGB) Trans (A)", 2D) = "white" { }
    }

    SubShader {
        Tags {
            "Queue"="Transparent"
            "RenderType"="Transparent"
        }

        CGPROGRAM
        #pragma surface surf Lambert alpha

        struct Input {
            float2 uv_MainTex;
            float4 color;
        };

        sampler2D _MainTex;
        fixed4 _Color;

        void surf(Input IN, inout SurfaceOutput o) {
            o.Albedo = tex2D(_MainTex, IN.uv_MainTex).rgb * IN.color.rgb * _Color.rgb;
            o.Alpha = tex2D(_MainTex, IN.uv_MainTex).a * IN.color.a * _Color.a;
            o.Specular = 0.2;
            o.Gloss = 1.0;
        }
        ENDCG
    }

    FallBack "Diffuse", 1
}

```

What is causing this issue, and how can I fix it?

# Answer
> 0 votes
Apparently all that was going wrong was happening when I declared the `Input` structure here:

> ```
> struct Input {
>     float2 uv_MainTex;
>     float4 color;
> };
>
> ```

All that was going wrong was going wrong due to the fact that I forgot to explicitly specify the `COLOR` semantic on this line:

> ```
> float4 color;
>
> ```

With the `COLOR` semantic specified, the above line of code should look like this:

```
float4 color : COLOR;

```

Always remember to specify your semantics when they're required.

---
Tags: shaders, unity
---


# Question
Title: How do I change the direction of a circle when it hits a corner?
I have a 2D Ball that might go against a wall.

If the Ball goes against the wall perpendicularly, it will just invert its direction (assuming no air resistance and no bounces that should make its speed change).

My problem is: how the velocity of the Ball changes when it goes against a corner?

This is the case I didn't figure out how to handle:

# Answer
Here is what I'd do:

Upon detection of the circle and the corner (this will be, IMHO, the most complicated thing to do), take the angle of the line segment between the centre of the circle and the corner (in RED), calculate the perpendicular to that (the tangent, in BLUE), and have the vector in (PURPLE) be reflected to the vector out (YELLOW).

It's probably the exact same thing that you're currently doing with the box sides, but instead of using a predefined tangent, you compute the tangent based on the position of the circle and the point of impact.
> 3 votes

---
Tags: 2d, physics
---


# Question
Title: Why are faces being drawn like this with my custom shader?
I've been writing a custom surface shader which allows for vertex colors (with alphas) to be set programmatically. From test runs of the shader itself, it works perfectly fine, and I am able to set the color of vertices programmatically. Unfortunately, I ran into some other issues. Currently, the shader is rendering mesh faces quite strangely, and I cannot figure out why:

The shader code itself currently looks like this:

```
Shader "Custom/VertexColorSurface" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" { }
    }

    SubShader {
        Tags { "RenderType"="Cutout" }

        CGPROGRAM
        #pragma surface surf Lambert alpha
        #pragma target 3.0

        struct Input {
            float2 uv_MainTex;
            float4 color : COLOR;
        };

        sampler2D _MainTex;
        fixed4 _Color;

        void surf(Input IN, inout SurfaceOutput OUT) {
            OUT.Albedo = tex2D(_MainTex, IN.uv_MainTex).rgb * _Color.rgb * IN.color.rgb;
            OUT.Alpha = tex2D(_MainTex, IN.uv_MainTex).a * _Color.a * IN.color.a;
            OUT.Specular = 0.2;
            OUT.Gloss = 1.0;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

Currently the two solutions I've tried have been using `ZWrite On` and `ColorMask 0` in a `Pass` block, and while both of these methods fix the face rendering issues, they totally screw up alpha blending, which is something I need.

What might be causing this issue, and how do I fix it?

# Answer
> 1 votes
This is caused by the order in which unity normally renders objects. Transparent objects are the glitchy exception to this order, as unity tries to calculate draw only one transparent object per pixel for what it thinks are opaque objects.

There are a few approaches to this issue. You could use the `Pass` solution with `Zwrite On` and `ColorMask 0`, but in your case, you may simply want to update your tags:

```
Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="TransparentCutout"}

```

For more info on what these tags are doing, check out SubShader Tags

Alternatively, if you don't want any transparency, you may want to consider using the "Standard" shader and select the "Cutout" rendering mode.

---
Tags: shaders, unity
---


# Question
Title: How to check strings from multiple lines in one input field?
I need help with input fields. I already set the line type to 'Multi\_Line NewLine' in inspector, but I have problem with submitting the string. Here's the code:

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class GameController : MonoBehaviour {
    public string code;
    public string code1;
    [SerializeField]
    public InputField input;

    public void Check(string guess)
    {
        if (string.Equals (guess,code)) {
            Debug.Log ("correct");
        } else
            Debug.Log ("wrong");
    }
    public void GetInput(string guess)
    {
        Check (guess);
        input.text = "";

    }
}

```

I want to have both 'code' and 'code1' strings to be inserted in different lines inside the same input field but I don't know how to check both 'code' and 'code1' string value inside the Check(). Any help would be appreciated.

# Answer
> 0 votes
I'm assuming `guess` variable will have a text from InputField, if so you could use this line to split the string from checking to NewLine

```
string[] guessWords = guess.Split('\n');

```

and then retrieving the specific word from the `guessWords` array like

```
if (string.Equals(guessWords[0], code))
{
    Debug.Log("code 1 correct");
}
else
{
    Debug.Log("code 1 wrong");
}
if (string.Equals(guessWords[1], code1))
{
    Debug.Log("code 2 correct");
}
else
{
    Debug.Log("code 2 wrong");
}

```

note you may still need to handle `IndexOutOfRangeException` if you only input one line to InputField

---
Tags: unity, c#, input
---


# Question
Title: How do I fix a delay between the first and second KeyEvent
I recently got really interested in making my own little game. As I have no real game development background I'm still figuring stuff out, but I encountered a little problem.

While working on the user input, I noticed a delay between the first and the second time the key event gets called.

Can somebody give me a tip on how I can fix it? I already had a method to make the changing a bit slower. But the input delay kinda broke the method.

Here you can see the problem https://gfycat.com/EvenCreepyAsianconstablebutterfly

As you can see from the console output I have a delay before the second activation.

```
    run_anim = new Image[4];
    try {
        sprite_idle = ImageIO.read(new File("img/sprite/base_.png"));
        run_anim[0] = ImageIO.read(new File("img/sprite/run_0.png"));
        run_anim[1] = ImageIO.read(new File("img/sprite/run_1.png"));
        run_anim[2] = ImageIO.read(new File("img/sprite/run_2.png"));
        run_anim[3] = ImageIO.read(new File("img/sprite/run_3.png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    spriteInx = run_anim.length;

    currentImage = sprite_idle;

```

Here is my key event:

```
public void keyPressed(KeyEvent e){
    int key = e.getKeyCode();

    for(int i = 0; i < handler.object.size(); i++){
        Entity temp  = handler.object.get(i);

        if(temp.getID() == ID.Player){
            //Player Control
            if(key == KeyEvent.VK_LEFT){
                System.out.println(System.currentTimeMillis());
                Player tempP = (Player) temp;
                tempP.startRun("left");
            }
            if(key == KeyEvent.VK_RIGHT) temp.setVelX(2);
        }
    }
}

```

I add my images in the constructor of the player

And here you get the code for my startRun method.

```
public void startRun(String string) {
    running = true;
    if(string.equals("left")){
        nextSprite(string);
    }

}

public void nextSprite(String dir) {
    if(running){
        if(dir.equals("left")){
                if(spriteCount < spriteInx-1){
                    currentImage = run_anim[spriteCount];
                    spriteCount++;
                }else{
                    spriteCount = 0;
                }

                currentImage = run_anim[spriteCount];
                setVelX(-2);
            }
        }
    else{
        currentImage = sprite_idle;
    }
}

```

If you need anything further, just tell me.

I use AWT and Swing and nothing like lwjgl or jmonkeyengine.

# Answer
> 1 votes
Instead of having the nextString method in the key event method, have it in a update method. Similar to the comment, it depends on the OS, so they won't always be the same. This might have sounded confusing, here's an example:

```
public void keyPressed(KeyEvent evt)
{
    if(evt.getKeyCode() == KeyEvent.VK_LEFT)
    {
        player.runMotion = -1;
    }
    if(evt.getKeyCode() == KeyEvent.VK_RIGHT)
    {
        player.runMotion = 1;
    }
}

```

Then in the player's update method, add the speed multiplied by the run motion to the player's velocity. Also, in the update method, run the next frame for the animation.

---
Tags: java, animation, sprites, keyboard
---


title: Get the difference between 2 matrices

text:
# Question
Title: Get the difference between 2 matrices
Hi I'm using `C#` and `MonoGame`, and have the world matrices of 2 objects. I need to get the difference between them, so I can effectively parent the second object onto the first. The aim is to get to a point where any changes to the parent transform can be applied to the child object too, by doing `child.Transform = parent.Transform * offset`.

I'm using the following code:

```
// ...

Matrix m1 = info.BoneTargets[i].Transform;
Matrix m2 = rigidbodyDefaultWorlds[transform.RigidBodyIndex];

Matrix transformFromTargetToRigidBody = Matrix.Invert(m1) * m2;
Debug.Assert((m1 * transformFromTargetToRigidBody).Equals(m2)); // FAIL

// ...

```

The Assert fails though, so I assume my math is wrong. I did try all other variations of the invert(a) * b formula though and none of them worked either.

For completion here are the matrix values:

```
M1  {M11:1 M12: 2.384186E-07 M13:-6.211763E-22 M14:0} {M21:0             M22:0             M23:1            M24:0} {M31:2.384186E-07  M32:-1            M33:0             M34:0} {M41:0.0005292654 M42:-0.03780181 M43:0.752234  M44:1}
M2  {M11:1 M12:-2.384186E-07 M13:0             M14:0} {M21:-3.884332E-14 M22:-1.629207E-07 M23:1            M24:0} {M31:-2.384186E-07 M32:-1            M33:-1.629207E-07 M34:0} {M41:0.01058531   M42:0.7560362   M43:-17.54894 M44:1}
TR  {M11:1 M12:-4.768372E-07 M13:-3.884332E-14 M14:0} {M21:4.768372E-07  M22:1             M23:1.629207E-07 M24:0} {M31:-3.884332E-14 M32:-1.629207E-07 M33:1             M34:0} {M41:0.01005606   M42:0.7938381   M43:-18.30118 M44:1}
OUT {M11:1 M12:-2.384186E-07 M13:-6.211763E-22 M14:0} {M21:-3.884332E-14 M22:-1.629207E-07 M23:1            M24:0} {M31:-2.384186E-07 M32:-1            M33:-1.629207E-07 M34:0} {M41:0.01058531   M42:0.7560362   M43:-17.54894 M44:1}

```

---

~~EDIT: Actually, now I'm thinking the formula is this...~~

~~child.World = childTransformWithOffsetTranslation * parentWorld~~

# Answer
> 3 votes
Your problem is that you're trying to compare floating-point numbers for equality. The matrix inversion and multiplication, however, will inevitable introduce slight rounding errors that will make the numbers in the two matrices not exactly equal.

Still, let's compare your debug printouts side by side. I've deleted the `M1` and `TR` rows, and left just the two that you're trying to compare:

```
M2  {M11:1 M12:-2.384186E-07 M13:0             M14:0} {M21:-3.884332E-14 M22:-1.629207E-07 M23:1            M24:0} {M31:-2.384186E-07 M32:-1            M33:-1.629207E-07 M34:0} {M41:0.01058531   M42:0.7560362   M43:-17.54894 M44:1}
OUT {M11:1 M12:-2.384186E-07 M13:-6.211763E-22 M14:0} {M21:-3.884332E-14 M22:-1.629207E-07 M23:1            M24:0} {M31:-2.384186E-07 M32:-1            M33:-1.629207E-07 M34:0} {M41:0.01058531   M42:0.7560362   M43:-17.54894 M44:1}

```

You can see that, in the printed output (which seems to be rounded to 7 significant digits of precision), the only *visible* difference is in cell (1,3), which is exactly zero in `M2`, but has a *very* small negative value -6.211763 × 10-22 in the product. How small is that? Well, let's write it out fully, without using scientific notation:

> -6.211763 × 10-22 = **-0.0000000000000000000006211763**

Yeah, that's basically as close to zero as to make no difference. But the `.Equals()` method will consider it to be different from zero (and will probably fail on other equally negligible differences, which are not visible in the printed output, as well).

For a more reasonable comparison, you could compare the matrix entries yourself one by one, using a "fuzzy comparison" function like the `nearlyEqual()` function from this answer on SO by Michael Borgwardt, quoted below:

```
public static boolean nearlyEqual(float a, float b, float epsilon) {
    final float absA = Math.abs(a);
    final float absB = Math.abs(b);
    final float diff = Math.abs(a - b);

    if (a == b) { // shortcut, handles infinities
        return true;
    } else if (a == 0 || b == 0 || diff < Float.MIN_NORMAL) {
        // a or b is zero or both are extremely close to it
        // relative error is less meaningful here
        return diff < (epsilon * Float.MIN_NORMAL);
    } else { // use relative error
        return diff / (absA + absB) < epsilon;
    }
}

```

The code above is Java, but converting it into C# should be trivial. I expect that your two matrices should be "nearly equal" at least to a precision of `epsilon = 1e-9`, and probably even closer.

# Answer
> 1 votes
I don't really understand your question to be honest but I think you're trying to figure out how to find the world matrix of a child node. In other words, you essentially have a scene graph with parent nodes and child nodes and you want to know how to calculate the world matrix of one of the children.

Essentially it's a two step process. First you need to calculate the local transform given that you already know the local position, rotation and scale relative to it's parent.

```
public Matrix GetLocalTransform()
{
    var rotationMatrix = Matrix.CreateRotationZ(Rotation);
    var scaleMatrix = Matrix.CreateScale(new Vector3(Scale.X, Scale.Y, 1));
    var translationMatrix = Matrix.CreateTranslation(new Vector3(Position.X, Position.Y, 0));
    var tempMatrix = Matrix.Multiply(scaleMatrix, rotationMatrix);
    return Matrix.Multiply(tempMatrix, translationMatrix);
}

```

Then once you have the local transform for a node you can multiply it by it's parent's world transform to get the world transform of this child.

```
public Matrix GetWorldTransform()
{
    return Parent == null ? Matrix.Identity : Matrix.Multiply(GetLocalTransform(), Parent.GetWorldTransform());
}

```

Of course, the top most parent node won't have a parent, so in that case you just use the identity matrix.

This works for an entire tree of nodes recursively.

The code above is from the MonoGame.Extended library if you want to take a closer look. It's a 2D scene graph, but the same principles should work for 3D scene graphs as well.

---
Tags: c#, mathematics, directx, monogame, matrix
---


# Question
Title: How to decide between strafing, turning etc for lateral character movement?
I have been studying the character movement of many 3rd person games. But just when I think I have come to understand the conventions or found a pattern, it seems I come across another game which does the complete opposite. I understand that there will always be games that defy conventions, but I am trying to work out at least some basic guidelines to follow.

For simplicity sake I have narrowed down lateral movement into 3 categories:

**1) Directional Movement**

This is movement where based on input of any of the four main directions (forward, back, left, right), the character will move in exactly that direction. In otherwords they will usually do a quick turn towards their direction and then walk straight in that direction. Therefore the character is always facing where they are going. The Assassin's Creed series is a good example of this.

**2) Strafing**

Most popular in FPS games, but also used in shooter heavy TPS games such as Gears of War and the Max Payne series. Here the character faces forward irrespective of which of the 4 main directions they are moving in, and therefore strafes when moving sideways.

**3) Turning**

This is similar to strafing except that when moving left or right the character will turn in that direction, moving in a circular way. Games that use this movement style include the GTA series and recently the Uncharted series.

So based on this I am trying to determine how to decide which movement type is best for which type of game. At the moment I am considering to use (2) for when aiming weapons (since this movement is used in FPS games), and (3) for all other ground based movement. But I am not sure if this is the best approach.

# Answer
> 3 votes
It depends primarily on what the player is supposed to do.

In games where a gun is facing in the walking direction and the main thing the player is supposed to do is to shoot things by accurately aiming the gun, it makes sense to point the camera and the gun in the same direction, so the player sees what they're shooting at. Disadvantages are that you can't look around without turning, and the camera usually turns very quickly, which will feel uncomfortable for some players and can cause nausea.

In a game where getting a good look of the surroundings is a lot more important than shooting people with a forward facing gun, you can decouple the walk and the view direction. This is especially important if the player will want to look in a certain direction without moving there. Disadvantages are that players not used to this control (or to video games in general) may have difficulties with controlling view and movement direction independently.

The two can be merged, by splitting camera and movement direction but instead of giving camera control to the player, the camera automatically follows the movement direction in a slow and smooth movement. This makes the control easier and reduces the risk of nausea, but also removes the ability to aim or to look somewhere without turning the character. This gives less control to the player, but allows the game to reach a wider audience.

You can even change the controls for different parts of the game, e.g. toggle to 1) whenever you enter/leave stealth mode, or toggle to 2) when you use a scoped aim mode.

The primary goal should be to reach a wide audience, which you do by choosing the least frustrating control scheme. By going for 3) you do that, but if the game is heavy on stealth or ranged combat, you will likely need to implement option 2) or option 1) as well, or the player might feel frustration due to the limited controls. And as soon as you're using 2 different control schemes, you need to consider if the game won't be simpler if you just use 1 control scheme instead.

---
Tags: game-design, movement, character
---


# Question
Title: How to handle global Data within a state machine setup? (C#)
I am currently building a turn-based framework (Unity,C#)

I was tired of my former tight-coupled systems and opted for a state machine this time, basically all components subscribe to the state-Enter and state-Exit event. I am aiming for scalability and structure.

But I ran into a problem. If the components cannot communicate directly, how to store and forward data in between states?

*Example: The game starts with unit placement. The player has the option to select a unit in his pool via the ui and place it on the board. The Unit-creation logic is and should(?) be handled inside the level script. How does it know where to create which unit? Ive done a workaround with a static container class, with is basically my clipboard. The player assigns a grid cell for his selected unit and the game leaves the state. While leaving the state the level scripts scans the clipboard and creates any assigned units.*

But I feel like a cheated my attempt to really work strictly within a firm structure this time to guide the design process.

Is there a better way?

# Answer
> 1 votes
Yes, setting a global variable and then calling a method which behaves differently based on its value is a dangerous anti-pattern known as "Accumulate and Fire". The remedy is to pass all data which is required by a method as parameters.

In your case the solution is to **not** use generic event handlers to enter a state. Give each state an unique `Enter` method with unique parameters which takes the arguments needed by that state and call these methods directly.

For example, `StateSelectUnit` switches to `StateGiveCommand` by calling `StateGiveCommand.Enter(selectedUnit)`. The semantic is that you do not enter a generic `StateGiveCommand`, you enter a *specific* `StateGiveCommand` for that unit, which is a different state than giving a command to a *different* unit.

# Answer
> 0 votes
A fine way to handle in a discrete way communications between entities is the Oberver pattern. Take a look at it.

each entity who need observation will need to add an observer to its list

```
public void AddObserver(Observer o)
{
    obs_l.Add(o);
}

```

Then when you define your Notify function you will baasically pass a reference to the object calling, if it is your need. Take a look of a sample of my Notify function:

```
protected void Notify(Object entity, KCEvent e, Object target, List<float> f_args, Vector3 pos, Quaternion rot)
    {
        foreach (var o in obs_l)
        {
            o.OnNotify(entity, e, target, f_args, pos, rot);
        }
    }

```

this is because when I notify observers what is happening I need to make them aware of a few things, like:

* entity, the Entity which notifies the event
* e, the event (just an enum in my case)
* target, another entity where the event could happen on
* f\_args, a list of float which represent different data needed by the observer to do things
* pos, is a position vector where things could happen
* rot, possibly a rotation needed to apply to something

All of these are purely chosen on my needs. You will do the same.
To answer you comment when I call Notify I will pass `this` as first parameter.

---
Tags: unity, events, state, turn-based, strategy
---


# Question
Title: Tips on thinking of a good game mechanic?
I am trying to make a turned based rpg and I really want to know how can i make original game mechanics like Undertale with it's sparing system.I am not really that creative to think of a good game mechanic,I just need tips on how to improve my creativity for game dev because it is really hard for me to think of something original. Thanks!

# Answer
You copy other ideas. Then by copying and mixing different other ideas, you'll find that they don't work very well together unless you make some adjustments . You do the adjustments (possibly by copying yet another idea from somewhere else) and then you have a new mechanic. At that point you might find that it still doesn't work well, in which case you need to start over.

Do not limit yourself to copying from computer games. You can also copy from board games, movies, reality, etc.
> 0 votes

---
Tags: game-design, game-mechanics, rpg
---


# Question
Title: Collision Between SKSpriteNode and SKShapeNode
I'm trying to create a collision between two objects. One is a `SKSpriteNode` and the other is a `SKShapeNode`. The code I have so far for determining contact is:

```
 func didBeginContact( contact: SKPhysicsContact) {
        let firstBody  : SKPhysicsBody = contact.bodyA
        let SecondBody : SKPhysicsBody = contact.bodyB

        if ((firstBody.categoryBitMask == PhysicsCatagory.Orange) && (SecondBody.categoryBitMask == PhysicsCatagory.Red)) || (firstBody.categoryBitMask == PhysicsCatagory.Red) && (SecondBody.categoryBitMask == PhysicsCatagory.Orange) {

            CollisionWithRed(firstBody.node as! SKSpriteNode, Red: SecondBody.node as! SKShapeNode)
        }

    }

    func CollisionWithRed (Orange: SKSpriteNode, Red:SKShapeNode){
       Orange.removeAllChildren()
       Red.removeAllChildren()
    }

```

The problem is that after the collision, the Orange and Red are not removed from the screen. They are still there.

The code for Orange is :

```
 func SpawnOranges () {
        let Orange = SKSpriteNode(imageNamed: "Orange.png")
        Orange.size = CGSize (width: 80, height: 80)
        let MinValue = self.size.width / 8
        let MaxValue = self.size.width - 20
        Orange.zPosition = 7
        let SpawnPoint = UInt32 (MaxValue - MinValue)
        Orange.position = CGPoint (x: CGFloat(arc4random_uniform(SpawnPoint)), y: self.size.height)
        Orange.physicsBody = SKPhysicsBody(rectangleOfSize:Orange.size)
        Orange.physicsBody?.categoryBitMask = PhysicsCatagory.Orange
        Orange.physicsBody?.affectedByGravity = false
        Orange.physicsBody?.dynamic = true
        Orange.physicsBody?.contactTestBitMask = PhysicsCatagory.red
        let action = SKAction.moveToY(-150, duration: 2.0)
        let actionDone = SKAction.removeFromParent()
        Orange.runAction(SKAction.sequence([action, actionDone]))

        addChild(Orange)

```

The code for Red is :

```
class Red: SKShapeNode{
    convenience init(path: UIBezierPath, color: UIColor, borderColor:UIColor) {
        self.init()
        self.path = path.CGPath
        self.fillColor = color
        self.strokeColor = borderColor

        Red = Red(path: projectilePath, color: UIColor.redColor(),
          borderColor: UIColor.blackColor())
        Red.position = Settings.Metrics.projectileRestPosition
        Red.zPosition = 7
        Red.name = "Square"
        Red.physicsBody = SKPhysicsBody()
        Red.physicsBody?.categoryBitMask = PhysicsCatagory.Orange
        Red.physicsBody?.affectedByGravity = false
        Red.physicsBody?.contactTestBitMask = PhysicsCatagory.Orange
        Red.physicsBody?.collisionBitMask = PhysicsCatagory.Orange
        Red.physicsBody?.dynamic = true
        Red.physicsBody?.affectedByGravity = false
        addChild(Red)

```

Any help would be extremely appreciated!

# Answer
You are removing their children which they don't have and to remove them you have to remove them from Parent. You can find more about children and parent Here

```
func CollisionWithRed (Orange: SKSpriteNode, Red:SKShapeNode){
       Orange.removeFromParent()
       Red.removeFromParent()
    }

```
> 1 votes

---
Tags: collision-detection, projectile-physics, swift
---


# Question
Title: How to assign a button in the main storyboard to launch the GameViewController.swift file
I am quite new to swift and I have constructed a main menu in the main.storyboard file, how do I assign the 'Play Now' button to launch the GameViewController.swift file where I actually plan to program the game.

# Answer
> 1 votes
Well you create your game in GameScene that is already linked to your GameViewController when you create a new project.

If you need a Main Menu Then you need to create another UIViewController in the MainStroyBoard and a swift class in the project.

Then you will have to link that class and UIViewController by clicking on the UIViewController and in properties tab you can select which class you want to link.

After that you will have to create a Segue when your **Play Button** is clicked you can find more about that HERE

Good Luck!

---
Tags: ios, xcode, swift
---


# Question
Title: How can I use tilt sensor in iOS iPad to steer a car?
I am an absolute beginner with Unreal Engine. I am working on a car racing project.

I need to navigate my car left and right using tilt

I read tilt sensor value then break vector to (X,Y,Z)

As show in the image, I need to read Y value. I call set steering input and pass this Y value.

# Answer
> 0 votes
after struggle with this issue I finally found the answer and I am here to share with all of you hope this help

---
Tags: ios, unreal-4
---