# Question
Title: How can I imbue an ability system with information about how abilities interact and can be targetted?
I am making a turn based game where player chooses a team of heroes with specific abilities for each of them. *(ex. stun one enemy, deal 20 damage to all enemies, heal 10 HP to one ally,...)*
The design right now is that every non-instant effect *(direct heal and damage are instant)* is placed as a buff/debuff on the hero. So once a spell affects an enemy it can apply a stun for 2 turns or a DoT for 3 turns, etc.

My problem is that whenever you click on an ability in the GUI, the game should show you who you can target, but enemies can have immunities to certain effects like immune to stun or immune to damage.
My first thought was to make an interface AbilityStun and then once I start checking for viable targets check in the immunity buff if the ability is an instance of a stun and if yes, don't show it as a viable target.

But I soon realized this is a bad solution because I have an ability which damages my own team member and stuns an opponent and it would show him as not viable. Or I want to apply a debuff that will disable healing abilities. Or I want to stun and deal damage.
Suddenly interfaces piled up and I would end up with 50 of them and a systems that feels like a hack.

I am pretty sure there is a better way of doing this but I simply can't figure it out even after looking through other similar articles. Maybe you guys (and girls) who are more experienced can be of more help and point me in the right direction.

Thank you for your help.

EDIT:

**Current Solution**

So I created a system based on CamH's answer. I have an ability which has information like cooldown, manacost, target, etc. and I added a group of **effects** to it. Effects can be either stun effect, heal effect, or any other effect in the future with required parameters like heal amount or stun duration as part of the effect.

Most importantly the effect has a group of **checks** that know what to look for in a group of buffs/debuffs and returns true/false based on whether the target passes the test.

***Example:*** *Hero A wants to cast a stun and damage spell on Hero B who is immune to stun. On target selection the Stun effect performs a check against Hero B's buffs and returns false since he is immune. The Damage check passes and since at least one check passed Hero B is a valid target.<br>After the ability lands every effect is applied separately and checks are performed again this time the stun won't apply and the damage takes place.*

The system is more complex than this but this part shows how I solved my problem with targeting and applying abilities.

# Answer
You could use some tags to determine what the immunities are of the opponent and what the effects are of the attack.

For example, you could give the opponent a tag "stun" and the attack a tag of "damage,stun". You could then check if the attack tag is equal to the opponent's tag and if so, prevent the move.

In the example, even though the enemy is immune to stun, they can still take damage. The attack will stun and do damage, however, the stun wouldn't work because it's immune to stun. So it will cancel the stun and still perform the damage. The opponents tags would be the immunities and the move's tags would be the effects so when running the move you can add effects appropriately.
> 2 votes

# Answer
I think you only need only one interface which you implement with all your abilities and which has only the method `bool canTarget(combatTarget)`.

Each ability would have an own implementation which checks if the target is a valid target. That check should be based on its allegiance and active immunities (although the implementation also allows more unique conditions).

Your target selection gui would check all available combat targets with that method and only show those where it returns true. Combat targets can also be "all allies" (abilities which affect the whole party), "all enemies" (abilities which affect all enemies) or "no particular target" (for abilities which affect all combatants equally or no combatants in particular).
> 0 votes

---
Tags: java, architecture, turn-based
---


# Question
Title: How do I calculate the tangent to a point on a circle?
I have a line that is from the center of a circle to a point on it's edge that is changing constantly (radius is drawn to a point orbiting a circle) I want to make a line tangential to the circle whose midpoint is always the orbiting point. I know how to do it on paper but coding it in logic is the problem. Can someone show me how or point me to resources that I could use that would help me?

```
    public Line calculateTangent(Circle ball){

    //the point orbiting the circle
    circleEdge = new Vector2f((float)(radius*Math.cos(angle*Math.PI/180f)), (float)(radius*Math.sin(angle*Math.PI/180f)));
    //the line that I want to be perpendicular to at all times
    radiusLine = new Line(ball.getCenterX(), ball.getCenterY(), circleEdge.getX(), circleEdge.getY());
    //no idea how to do this last part
    perpendicular =

    }

```

# Answer
> 2 votes
In 2D there's a simple trick for getting a perpendicular vector:

```
Vector2 Rotate90(Vector2 original)
{
    return new Vector2(original.y, -original.x);
}

```

(ie. swap the vector's x & y components and negate one of them)

Whether this rotates the vector clockwise or counterclockwise depends on your coordinate system. If it's pointing the wrong way for your use case, just put the negative sign on `original.y` instead of `original.x`

# Answer
> 1 votes
The cross product of two vectors is a third vector that is perpendicular to both inputs.

```
public Line calculateTangent(Circle ball)
{
  //Unit circle at (0,0,0)
  //Vector3, radius = 1.0f
  circleEdge = new Vector3((float)(Math.cos(angle*Math.PI/180f)), 0, (float)(Math.sin(angle*Math.PI/180f)));

  //Visual only
  radiusLine = new Line(ball.getCenterX(), ball.getCenterY(), circleEdge.getX(), circleEdge.getY());

  //Circle lies in XZ plane so (0,1,0) is perpendicular to any point on the circumference
  //perpendicular must be perpendicular to both circleEdge and (0,1,0)
  //Result of cross-product is a direction away from (0,0,0)
  perpendicular = circleEdge.Cross(Vector3(0, 1, 0));

  //Unit circle has convenient radius of 1.0f
  //Scale to correct radius
  circleEdge *= radius;

  //Everything is at (0,0,0)
  //Translate to real position
  circleEdge += ball.Center();

  //perpendicular is a direction away from (0,0,0)
  //Convert to direction away from circleEdge
  perpendicular += circleEdge;
}

```

---
Tags: java, geometry, slick
---


# Question
Title: Box2D is not positioned on the sprite correctly LibGDX
I have a strange issue where my Box2D is not being positioned on the player correctly. Down is the picture:

What I find more strange is that the Box2D is positioned correctly on the cloud that is below my player, and I use the same code for both.

The code for creating the body for the player:

public class Player extends Sprite {

```
public World world;
public Body body;

public Player() {
    super(new Texture(Gdx.files.internal("Player/Player 1.png")));
}

public Player(World world, float x, float y) {
    super(new Texture(Gdx.files.internal("Player/Player 1.png")));
    this.world = world;
    setPosition(x, y);
    createBody();
}

void createBody() {

    BodyDef bodyDef = new BodyDef();

    // dynamic body is affected by other forces e.g. gravity and it has velocity
    // static body is not affected by other forces gravity and it does not have velocity
    // kinematic body is not affected by gravity but it can be manipulated by velocity
    bodyDef.type = BodyDef.BodyType.DynamicBody;

    bodyDef.position.set(getX(), getY());

    // create body in the world using our definition
    body = world.createBody(bodyDef);

    // define the dimensions of the physics shape
    PolygonShape shape = new PolygonShape();

    shape.setAsBox(getWidth() / 2, getHeight() / 2);

    // FixtureDef is a confusing expression for physical properties
    // Basically this is where you, in addition to defining the shape of the body
    // you also define it's properties like density, restitution and others
    // If you are wondering, density and area are used to calculate over all mass
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.density = 1f;

    Fixture fixture = body.createFixture(fixtureDef);

    // shape is disposable now so get rid of it
    shape.dispose();

} // create body

public void updatePlayer() {
    this.setPosition(body.getPosition().x, body.getPosition().y);
}

```

} // class

The code for creating the body for the cloud:

```
public class Clouds extends Sprite {

private World world;
private Body body;

public Clouds(World world, float x, float y) {
    super(new Texture(Gdx.files.internal("Clouds/Cloud 1.png")));
    this.world = world;
    setPosition(x - getWidth() / 2, y);
    createClouds();
}

void createClouds() {

    BodyDef bodyDef = new BodyDef();

    // dynamic body is affected by other forces e.g. gravity and it has velocity
    // static body is not affected by other forces gravity and it does not have velocity
    // kinematic body is not affected by gravity but it can be manipulated by velocity
    bodyDef.type = BodyDef.BodyType.StaticBody;

    bodyDef.position.set(this.getX() + getWidth() / 2,
            this.getY() + (getHeight() / 2 - 10));

    // create body in the world using our definition
    body = world.createBody(bodyDef);

    // define the dimensions of the physics shape
    PolygonShape shape = new PolygonShape();

    shape.setAsBox(this.getWidth() / 2, this.getHeight() / 2);

    // FixtureDef is a confusing expression for physical properties
    // Basically this is where you, in addition to defining the shape of the body
    // you also define it's properties like density, restitution and others
    // If you are wondering, density and area are used to calculate over all mass
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.density = 1f;

    Fixture fixture = body.createFixture(fixtureDef);

    // shape is disposable now so get rid of it
    shape.dispose();

} // create body

```

} // class

And here is where I'm creating the player and the cloud and adding them in my game world:

```
public class Gameplay implements Screen {

GameMain game;

private OrthographicCamera camera;
private Viewport gameViewport;

Texture bg;

private Hud hud;

private Player player;

private World world;

// delete this later
private Box2DDebugRenderer b2Renderer;

Clouds cloud;

public Gameplay(GameMain game) {

    this.game = game;
    camera = new OrthographicCamera(GameInfo.WIDTH, GameInfo.HEIGHT);

    camera.position.set(GameInfo.WIDTH / 2f,
            GameInfo.HEIGHT / 2f, 0);

    gameViewport = new StretchViewport(GameInfo.WIDTH, GameInfo.HEIGHT, camera);

    bg = new Texture(Gdx.files.internal("Backgrounds/Game BG.png"));
    hud = new Hud(this.game.batch);

    world = new World(new Vector2(0, -98), true);
    b2Renderer = new Box2DDebugRenderer();

    player = new Player(world,
            GameInfo.WIDTH / 2,
            GameInfo.HEIGHT/ 2 + 100);

    cloud = new Clouds(world,
            GameInfo.WIDTH / 2,
            GameInfo.HEIGHT/ 2 - 100);

}

@Override
public void show() {

}

@Override
public void render(float delta) {

    // update the physics world
    world.step(Gdx.graphics.getDeltaTime(), 6, 2);

    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    game.batch.begin();
    game.batch.draw(bg, 0, 0);
    game.batch.draw(cloud, cloud.getX(), cloud.getY());
    game.batch.draw(player, player.getX(), player.getY());
    game.batch.end();

    b2Renderer.render(world, gameViewport.getCamera().combined);

    game.batch.setProjectionMatrix(hud.stage.getCamera().combined);
    hud.stage.draw();

    player.updatePlayer();

}

@Override
public void resize(int width, int height) {
    gameViewport.update(width, height);
}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void hide() {

}

@Override
public void dispose() {
    bg.dispose();
    world.dispose();
    b2Renderer.dispose();
}

```

} // class

Is it possible that the issue is with the sprite itself, maybe when the sprite is created in photoshop? Or am I missing something here?

Any help would be greatly appreciated.

P.S. - GameInfo.Width is 480 and GameInfo.Height is 800 if that can help someone figure this out.

# Answer
> 0 votes
Finally fixed it.

I ended up typing thins:

```
public void updatePlayer() {
    this.setPosition(body.getPosition().x - getWidth() / 2f,
            body.getPosition().y - getHeight() / 2f);
}

```

instead of this:

```
public void updatePlayer() {
    this.setPosition(body.getPosition().x, body.getPosition().y);
}

```

But its really strange that this code did not work:

```
bodyDef.position.set(getX(), getY());

```

or this code did not also work:

```
bodyDef.position.set(getX() - getWidth() / 2f,
            getY() - getHeight() / 2);

```

And whats even more strange the same code worked for the cloud.

But as I said, finally found the solution, thank you all for your help.

# Answer
> 2 votes
Try changing from this bodyDef.position.set(getX(), getY()); to this bodyDef.position.set(getX() + getWidth () / 2.0f, getY() + getHeight () / 2.0f);

When setting the position of the `BodyDef` for the player.

---
Tags: libgdx, box2d
---


# Question
Title: Boolean change when clicking the left mouse button (not working)
I want to change a boolean when I click the left mouse button, but it doesn't work as expected. I use this method:

```
if (m.LeftButton == ButtonState.Released && m_Old.LeftButton == ButtonState.Pressed)
{
   if (second)
   {
      second = false; // Boolean changes
   } else
   {
      second = true; // Boolean changes
   }
}

```

I need a way to tell the code that I only want one change. When I click the left mousebutton, the **second** boolean changes constantly. The reason for this is that the code keeps executing until **m\_Old** (the old mousestate) is updated. (m & m\_Old must be different for this code to run)

An example (when I click the left mouse button once| these are the results for the **second** boolean):

My mouse update code:

```
// Mouse stuff
oldMouse = mouse;
mouse = Mouse.GetState();

```

# Answer
> 0 votes
Ah I think I understand the problem now. It's not really clear from the code you've posted what the problem is but I think it might have something to do with `second` being declared in the local scope.

I tested the code below and I believe it's working as you'd expect. I've renamed some of the variables to hopefully make it a little more understandable. It wasn't really clear from the question if `second` is a member variable but I believe it needs to be to maintain state across refreshes.

```
private MouseState _previousMouseState;
private bool _second;

protected override void Update(GameTime gameTime)
{
    var mouseState = Mouse.GetState();

    if(mouseState.LeftButton == ButtonState.Released && _previousMouseState.LeftButton == ButtonState.Pressed)
    {
        _second = !_second;
    }

    _previousMouseState = mouseState;

    base.Update(gameTime);
}

```

Since you're essentially just flipping a flag the if statement in the middle can be reduced to one line. Either way should work though.

---
Tags: c#, monogame, mouse
---


# Question
Title: LibGDX: How to detect remote button press for Android TV?
On Android TV, I need to be able to detect the remote control centre button to start the game.

I tried:

```
if (Gdx.input.justTouched() || Gdx.input.isKeyJustPressed(Input.Keys.SPACE) || Gdx.input.isKeyJustPressed(Input.Keys.DPAD_CENTER) ||
                Gdx.input.isKeyJustPressed(Input.Keys.ENTER) ||
                Gdx.input.isKeyJustPressed(Input.Keys.BUTTON_SELECT) ||
                Gdx.input.isKeyJustPressed(Input.Keys.BUTTON_START))  {
...}

```

All does not work. The only one that works is isKeyPressed(Input.Keys.DPAD\_CENTER), but that will return more than one key pressed.

# Answer
> 1 votes
This is pretty late but try `Gdx.input.isKeyJustPressed(Input.Keys.CENTER)`. That works for my Nvidia Shield remote. Also as a side not this is also the A button on the Nvidia Shield controller.

---
Tags: android, libgdx, keyboard
---


# Question
Title: Instantiate a 2D GameObject in certain direction
I'm working in a Top-Down 2D Game, and i'm trying to avoid the use of rigidbodies and rotations, i manage the direction the player is facing via input and changing the sprites, but right now, i dont know how to shoot a bullet in the direction i'm facing.

I check the direction with the current SpriteRenderer.sprite, but i dont know how to Instantiate a GameObject like

```
Instantiate(bullet, transform.position, /** One of the Four Angles like (0,90,180,270)*/);

```

Any idea on how to aproach this?

Thank you.

# Answer
You just need to create a Quaternion with the appropriate rotation. Since you're top-down, you can create a rotation around the up axis (or the forward axis, depending on how you have things laid out).

```
Quaternion.AngleAxis(90, Vector3.up)

```

So,

```
Instantiate(bullet, transform.position, Quaternion.AngleAxis(180, Vector3.up));

```

For other info about creating 2D games, check out the Unity tutorials for 2D Game Creation.
> 3 votes

# Answer
For future reference, i'm posting how i got this to work.

```
//I just change the current sprite through Input
//And move the bullet with
//tranform.Translate(Vector2.right * speed) inside their own script

void ShootingManager(){

    if(spriteRenderer.sprite == sprite_left){
        Instantiate (bullet, this.transform.position, Quaternion.AngleAxis (180, Vector3.forward));
    }
    else if(spriteRenderer.sprite == sprite_right){
        Instantiate (bullet, this.transform.position, Quaternion.AngleAxis (0, Vector3.forward));
    }
    else if(spriteRenderer.sprite == sprite_up){
        Instantiate (bullet, this.transform.position, Quaternion.AngleAxis (270, Vector3.forward));
    }
    else if(spriteRenderer.sprite == sprite_down){
        Instantiate (bullet, this.transform.position, Quaternion.AngleAxis (90, Vector3.forward));
    }

}

```
> 0 votes

---
Tags: unity, 2d
---


# Question
Title: opengl storing multiple indices into indices buffer
After parsing collada files I found out that we have to load two(or more) indices each pointing to say a vertex or normal etc. like this (\<p\>3 0 2 0 0 0\</p\>)

Is there a way to load (and use)these indices to indices buffer(`ELEMENT_ARRAY_BUFFER`) like this (vnvnvn...)
; where v is vertex pointer, n is normal pointer from the above.

with vertices loaded to VBO1 like (vvvv...) and in VBO2 like (nnnn...). So that we dont have to repeat the normals in VBO2.

VBO like (vnvnvn...) is also ok.

(and not something like this https://stackoverflow.com/questions/11148567/rendering-meshes-with-multiple-indices), I'm not trying to use multiple indices buffer. I'm trying to put all the given indices into one index buffer and use them alternately.

(If I wasnt clear i will try for more clarification.)

# Answer
> 0 votes
If you're using the built-in vertex attribute gathering from vertex buffer bindings, a single numeric index is all you can use as indexes are used directly by the API.

This is immutable and cannot change, each element from the index buffer is used to gather attributes from the same offset in each bound attribute buffer.

A neat technique you may want to look at is that you can instead bind your geometry as textures or SSBOs to your shader and draw with no buffers bound, relying on `gl_VertexID` in the shader to sample from your geometry sources, where `my_Positions` is such a buffer and `my_Indices` is a buffer of indices.

`gl_VertexID` is a shader-visible integer that holds the value of the index of the current vertex being transformed. If you draw with an index buffer, it's the index, if you draw unindexed geometry, it's in a linearly increasing sequence of `0,1,2...`. By drawing geometry with N unindexed vertices with no index buffers and vertex buffers bound in the VAO, you can do the attribute sampling yourself in your shader like:

```
vec4 position = my_Positions[my_Indices[gl_VertexID]];
vec3 normal = my_Normals[my_Indices[gl_VertexID]];

```

This can trivially be extended into multiple index sources:

```
vec4 position = my_Positions[my_PositionIndices[gl_VertexID]];
vec3 normal = my_Normals[my_NormalIndices[gl_VertexID]];

```

If your indices are small enough, you can avoid binding separate buffers for indices and use the built-in element buffer by packing all your indices into a single R32 index, like `idx = ((pIdx & 0xFFFF) << 16 | (nIdx & 0xFFFF))`. You still have to do the manual sampling in your shader, as the built-in index lookup would overshoot any bound buffers.

---
Tags: opengl, index-buffer
---


title: Luminance 'y' value of surface texture

text:
# Question
Title: Luminance 'y' value of surface texture
For my opengl video player app, I am using surface texture bound to GL\_TEXTURE\_EXTERNAL\_OES

source : https://github.com/crossle/MediaPlayerSurface/blob/master/src/me/crossle/demo/surfacetexture/VideoSurfaceView.java

In my fragment shader, I want luminance value to be taken for 3x3 block.

```
vec2 tex00 = vec2(vTextureCoord.x-xmargin, vTextureCoord.y-ymargin)
vec4 p00 = texture2D(sTexture, tex00)

... etc for 3x3

```

and then calculate luminance of each texel : ie: p00 by doing dot of p00.rgb with vec3 of (0.3,0.59,0.11).

Instead is it possible to directly use p00.y ? Will it give luminance value?

# Answer
> 2 votes
No, it will not. In GLSL vectors have three sets of swizzle masks: `xyzw`, `rgba` and `stpq`. The implied semantics (coordinates, color and texture coordinates) are there to help the developer only. They all access the same set of data.

`p00.y`, `p00.g` and `p00.t` will all return the same value, in this case the green component of the texel.

---
Tags: textures, opengl-es, fragment-shader
---


# Question
Title: Storing coordinates of every object in server side in MMOs
In an MMORPG:

Is it typical or feasible to store the coordinates of every tree, bush rock.. etc in the server side for collision detection?

If so, what would be a feasible way to store such a huge number of coordinates (data structures and such, performance issues handling)?

If not, is this type of collision detection done entirely in the client side, with the server not checking at all?

Or is there a middle ground, with the client checking collision and server verifying? If so, how would the server verify the same without keeping the coordinates in the server as well?

# Answer
Independent of feasibility (yes, depending on scale) there are often better or easier ways.

For instance, in your typical MMO, the server really only needs to know about the coarse navigation map used by AI and player pathfinding. Instead of storing the location of a tree, you can instead just cut a hole into the navmap at the location of the tree. Likewise for any other big obstacles.

Even games that need more in-depth collision detection, you can often break this into server- and client-side detection. The server can just concern itself with coarse pathing while the client handles more animation-sensitive collision detection. For instance, a wounded player tries to crawl along a big rock to find a hiding place from enemies. The server determines that a player could move along the edge of the rock (the server has no idea that there *is* a rock, just that there's a path the player can take next to an unpathable area) while the client knows that the rock is present and plays an animation of the character propping itself against the rock as it walks. Note that the client isn't *moving* the character or impacting gameplay in any way in this case; it's just reacting to the nearby objects with an animation.

You certainly can store large numbers of objects on the server. It's no different than any open-world game. Use a good spatial partitioning scheme and keep the memory footprint of your objects as light as you can. Note that we may have different versions of "large numbers" in our heads here: if you meant that you wanted to store every little pebble or rocky bump in the game as a separate object then that's just silly, even for a single-player game. :)
> 15 votes

# Answer
Yes - it is feasible. MMOs often split the game world into multiple areas, as this makes the job easier, but you can still do it with 1 massive area - you just need to use a good spatial partitioning scheme.

Because most objects in MMOs don't move, you can also perform a preprocessing pass where objects are used to create collision checking trees.

Memory footprint isn't a huge issue here as long as you use instancing. Storing a couple floats per object is nothing in the grand scheme of things. A modest PC nowadays will have 4 gigabytes, while storing a position is just 3 floats (or 3 doubles) - which would easily allow several million stored objects in-game.

Storing things like inventories for each player would undoubtedly take up more data - although that can easily be cached to disk and only loaded when a player logs in.

You'll want to redundantly do the collision checking on the client as well as the server, as this'll allow the client to more responsively react to the environment. If a player walks into a wall, you want them to stop moving immediately - not after half a second when the server responds.

You only want to use the server for authoritative things, too. For example, you would perform pathfinding only on the client, as you can't cheat by taking a less efficient path!
> 7 votes

---
Tags: collision-detection, collision-resolution, mmo, server
---


# Question
Title: Unity LineRenderer custom reapeted Texture with margin
I have a LineRenderer, which has 1 dot as texture, which is repeated over the whole line. Now I want to know, if there is some way to give this dots a margin, so that I can make the gap between them bigger.

For the moment there is no gap, I could make a new Texture and add the margin there, but I hope for some more dynamic way to do this.

Edit: Inspector View :

# Answer
> 6 votes
If all you need are dots, I wouldn't even use a texture for this. We can shape a repeated circular zone to our liking within the shader:

By playing with the Repeat Count and Spacing material parameters, you can change the number & spacing of the dots. Offset will shift the dot pattern along the line.

Here's the shader I wrote for this:

```
Shader "Unlit/DottedLineShader"
{
    Properties
    {
        _RepeatCount("Repeat Count", float) = 5
        _Spacing("Spacing", float) = 0.5
        _Offset("Offset", float) = 0
    }
        SubShader
    {
        Tags { "RenderType" = "Transparent" "Queue" = "Transparent" }
        LOD 100

        Blend SrcAlpha OneMinusSrcAlpha
        ZWrite Off

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            float _RepeatCount;
            float _Spacing;
            float _Offset;

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
                fixed4 color : COLOR0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
                fixed4 color : COLOR0;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
                o.uv = v.uv;
                o.uv.x = (o.uv.x + _Offset) * _RepeatCount * (1.0f + _Spacing);
                o.color = v.color;

                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                i.uv.x = fmod(i.uv.x, 1.0f + _Spacing);
                float r = length(i.uv - float2(1.0f + _Spacing, 1.0f) * 0.5f) * 2.0f;

                fixed4 color = i.color;
                color.a *= saturate((0.99f - r) * 100.0f);

                return color;
            }
            ENDCG
        }
    }
}

```

One little issue: in my test scene this gets rendered behind the skybox. I'm used to "Queue"="Transparent" fixing that, so I may have something else a little off in here, but I don't have time to debug right now. If it poses a problem for you, you can make the dots alpha tested instead of blended as a quick & dirty fix.

---
Tags: textures, unity
---


title: Why is my deltaTime in my GameLoop 0?

text:
# Question
Title: Why is my deltaTime in my GameLoop 0?
I have a question about my code. I wrote a basic GameLoop for an Android Game and while testing it I realized the deltaTime is always 0.

The code looks like this:

```
@Override
 public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        lastTime = System.currentTimeMillis();
    }

@Override
    public void onDrawFrame(GL10 gl) {
        float currTime = System.currentTimeMillis();
        float deltaTime = currTime - lastTime;
        float msPerFrame = 1000.0f/ 60.0f;

        if(deltaTime < msPerFrame){
            try {
                Thread.sleep((long)(msPerFrame-deltaTime));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        update(deltaTime, gl);
        lastTime = currTime;

    }

    public void update(float deltaTime, GL10 gl){
           //doStuff
    }

```

lastTime and currTime are always the same and the deltaTime is 0. I don't know if this is right or the code is just wrong but I think the deltaTime shouldn't be 0...

I test the app with Android Studios Emulator.

# Answer
All those time functions work with the datatype `long`. Try changing `float` to `long` to avoid potential rounding errors.

`currentTimeMillis()` might not be accurate enough. Try `System.nanoTime()` instead: https://stackoverflow.com/questions/351565/system-currenttimemillis-vs-system-nanotime
> 1 votes

---
Tags: java, android, game-loop
---


# Question
Title: Getting input from just one Axis at a time
I'm trying to make a `CharacterController2D` Script for a simple 2D TopDown game, but i was wondering, what would be the best way to disable 2-axis movement? just allowing one direction at a time (Maybe similar to the old Pokemon games)

# Answer
You can use Input.GetKeyDown and Input.GetKeyUp and do something like:

Uses `GetKeyDown` to test if your "Move on X axis" key is pressed, if true, disable moving on the Y axis by setting a flag. Do the same for the Y axis.

Now you just need to use `GetKeyUp` to reset a flag on a particular axis. ie. if the "Move on Y axis" key is released, you have to reset the flag preventing you from moving on X axis.

```
if (canMoveOnX && Input.GetKeyDown(X_KEY))
{
    canMoveOnY = false;
    Move(X);
}
if (canMonveOnY && Input.GetKeyDown(Y_KEY))
{
    canMoveOnX = false;
    Move(Y);
}

if (Input.GetKeyUp(X_KEY))
{
    canMoveOnY = true;
}
if (Input.GetKeyUp(Y_KEY))
{
    canMoveOnX = true;
}

```
> 1 votes

# Answer
I don't know if you decided to use GetAxis or GetKey... but you can compare both axis everytime the player can move (when the move animation is over) and use only the more important one. As GetAxis returns a value between -1.0f and 1.0f if you check the absolute value of both axis then you'd know which direction is asked by the player.

For example:

```
float horizontal = Input.GetAxis("horizontal");
float vertical = Input.GetAxis("vertical");

if ( horizontal != 0.0f || vertical != 0.0f ) // if player asked to move
{
    // if the pressure is more important on the horizontal axis
    if ( Mathf.Abs(horizontal) >= Mathf.Abs(vertical) ) // note that if both values are equals the default behaviour will be to chose horizontal axis.
    {
        // Move on horizontal axis
    }
    else
    {
        // Move on vertical axis
    }
}

```
> 1 votes

---
Tags: unity, 2d, movement, input
---


title: OpenGL EBO vs Mesh representation

text:
# Question
Title: OpenGL EBO vs Mesh representation
As an exercise set to myself, I wanted to make a Mesh loader using modern OpenGL.

However, I have to ways of representing the notion of *face* of a mesh.

Currently, I am using what seems the most natural. A mesh contains a

```
std::vector<Triangle>

```

and a Triangle is simply

```
struct Triangle
{
    unsigned int Vertices[3];
}

```

(i.e. each triangle stores the three indices of its vertices). NOTE : a mesh contains others things (such as the vertices and the normals but I didn't include them here for simplicity).

However, OpenGL require a different representation for using EBO : only one static array on indices (implicitly grouped by 3).

What I have come up with is a trade-off between these representations : once the mesh is loaded, I generate a static array of size

```
3 * mesh->Faces.size()

```

but I assume this is not the best option for memory use and redundancy.

So my questions are :

* If I want to keep my current representation of a mesh (with a vector of faces), how should I set OpenGL to properly render such a mesh ? Is my current solution of generating a new static a good practice ?
* Assuming I can use the representation I want for my mesh. What would you recommand and why ?

# Answer
> 0 votes
Actually your current way is fine.

C++ struct layout will let you turn the `Triangle*` into a `int*` and store that into the EBO.

---
Tags: opengl, 3d-meshes
---


# Question
Title: Accessing motor object of a surface motor
I would like to make a door closer for a door. The door should open normally, but when the person passes through close slowly. I've made an standard door on hinges, but then made one of them a motor and thought to control it when the person passes the door. However, I can't find the motor object on that part which owns the motor-surface. How can I do this properly?

# Answer
A surface motor is undesirable in this case. Unless you want to dig through JointsService to find the actual instance of the motor, the only control you have over that instance is through the corresponding ParamB property of the part the motor is adorned to. This only gives you control over the rotational speed of the motor, it does not allow you to set a desired angle.

I instead recommend keeping the door on hinges but using a BodyGyro to close it. In this case, simply insert a BodyGyro into the part you are using for your door and set the cframe of the BodyGyro to that of the door part. When you want a player to open the door, simply lower or remove the torque of the BodyGyro. When you want to close the door, increase the torque.

```
local door = script.Parent
local bodyGyro = Instance.new("BodyGyro", door)
bodyGyro.cframe = door.CFrame

local closingTorque = 10 * door:GetMass()

local function OnTouched(otherPart)
    if game.Players:GetPlayerFromCharacter(otherPart.Parent) then
        bodyGyro.maxTorque = Vector3.new(0, 0, 0)
        wait(2)
        bodyGyro.maxTorque = Vector3.new(0, closingTorque, 0)
    end
end

door.Touched:connect(OnTouched)

```

You will have to fiddle with closingTorque to get the behavior you want. Note that it is useful to scale this by the mass of the object to account for doors made with different materials. You could do the math to calculate the exact torque you need to close the door in an exact amount of time, but usually a ballpark will do.
> 3 votes

---
Tags: roblox
---


# Question
Title: Comparison of two 2d top down player movement scripts in Unity
I have been following along two different tutorials on making an 2d RPG and comparing the two movement scripts that seem to do the same thing but in different ways. Which is a better way when comparing these scripts?

```
using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    public float moveSpeed;
    private Animator anim;

    // Use this for initialization
    void Start () {
        anim = GetComponent<Animator> ();
    }

    // Update is called once per frame
    void Update () {
        if(Input.GetAxisRaw ("Horizontal") > 0.5f || Input.GetAxisRaw ("Horizontal") < -0.5f){
            transform.Translate(new Vector3(Input.GetAxisRaw ("Horizontal") * moveSpeed * Time.deltaTime, 0f, 0f));
        }

        if(Input.GetAxisRaw ("Vertical") > 0.5f || Input.GetAxisRaw ("Vertical") < -0.5f){
            transform.Translate(new Vector3(0f, Input.GetAxisRaw ("Vertical") * moveSpeed * Time.deltaTime, 0f));
        }

        anim.SetFloat ("MoveX", Input.GetAxisRaw("Horizontal"));
        anim.SetFloat ("MoveY", Input.GetAxisRaw("Vertical"));
    }
}

```

Script 2:

using UnityEngine; using System.Collections;

```
public class PlayerMovement : MonoBehaviour {
    Rigidbody2D rbody;
    Animator anim;

    // Use this for initialization
    void Start () {
        rbody = GetComponent<Rigidbody2D> ();
        anim = GetComponent<Animator> ();
    }

    // Update is called once per frame
    void FixedUpdate () {
        Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

        if (movement_vector != Vector2.zero) {
            anim.SetBool ("Iswalking", true);
            anim.SetFloat ("Input_x", movement_vector.x);
            anim.SetFloat ("Input_y", movement_vector.y);
        } else {
            anim.SetBool ("Iswalking", false);
        }

        rbody.MovePosition (rbody.position + movement_vector * Time.deltaTime);
    }
}

```

# Answer
Actually, you're comparing `transform.Translate()` with `rigidbody.MovePosition()`.

As you probably know, **transform** represents the **coordinate information of the object** (position, rotation, scale), whereas the **rigidbody** is used to **control the position of the object through physics**.

So, the first knows nothing about physics, the second does. If you are using physics you may bump into glitches if you're using `transform.Translate()`, `rigidbody.MovePosition()` on the contrary handles correctly physics situation.

Collisions between objects moved around using `transform.Translate()`, for example, may result in unwanted overlaps of objects.
> 0 votes

---
Tags: unity, 2d, rpg
---


# Question
Title: How decoupled should game logic and rendering be?
From a data perspective, how decoupled should game logic and rendering be? How much does it have to know about each other?

Take a look at the following example. I'm going to use javascript because that's what I'm most familiar with.

**Block**

*Basically, when the Block.destroy is called, there is a delay before it loses a life*

```
function Block(life, destructionDelay){
    this.life = life;
    this.destructionDelay = destructionDelay;

    this.destructionCountdown = 0;
}

Block.prototype = {
    destroy: function(){
        this.destructionCountdown = this.destructionDelay;
    },

    update: function(){
        if(this.destructionCountdown > 0){
            this.destructionCountdown--;

            if(this.destructionCountdown === 0){
                life--;
            }
        }
    }
}

```

What was supposed to happen here is when the Block is destroyed, it plays a "being destroyed" animation before it loses a life/destroyed.

As I have been informed, it is ideal for the game logic to know nothing/minimal about the renderer and vice-versa. How do I design these kinds of entities?

# Answer
As completely as possible. Each sub-system within the game should be able to operate with minimal dependencies. A popular method is called the Entity-Component-System.

> Game example
> Suppose there is a drawing function. This would be a "System" that iterates through all entities that have both a physical and a visible component, and draws them. The visible component could typically have some information about how an entity should look (e.g. human, monster, sparks flying around, flying arrow), and use the physical component to know where to draw it.
>
> Another system could be collision detection. It would iterate through all entities that have a physical component, as it would not care how the entity is drawn. This system would then, for instance, detect arrows that collide with monsters, and generate an event when that happens. It should not need to understand what an arrow is, and what it means when another object is hit by an arrow.
>
> Yet another component could be health data, and a system that manages health. Health components would be attached to the human and monster entities, but not to arrow entities. The health management system would subscribe to the event generated from collisions and update health accordingly. This system could also know and then iterate through all entities with the health component, and regenerate health.

In this way, the only difference between a Block and any other entity in your game is the set of behaviors attached to them. Attaching a behavior to Block causes that behavior system to affect all instances of Block the same way.

Using your example, the "health system" would respond to some input (a collision event?) and set the initial "life" (`Block.destroy()`). When the health system updates, the Block's life is drained. When the Block has no life left, the health system calls `Block.DestroyForReal()` which removes the dead Block instance from all systems.

As a real-life analogue, it makes no difference what type of machine a gear is installed in. Regardless of what the machine does, an individual gear has only one behavior; to turn. Likewise, when you are driving a car, the engine doesn't worry about things like "low fuel", that is the responsibility of the driver-system. The driver **only** fills the fuel-system; the engine **only** empties it.

If I were going to do this in Unity, I'd have a "health" (stop-watch) script and the "animator" (animate model transforms) script. When I click a Block, the health script is attached to the block and initialized. It runs on its' own and, when the count-down is finished, removes itself and adds the animator script. The animator script does nothing but integrate deltaTime into the model's bone-transforms (which the renderer uses). When the animation is complete, the animator script is detached and the Block is disabled/destroyed. The renderer does not care which scripts are attached to the Block and/or what they are doing to it.

Here is the "health-system" for an Arkanoid-style Brick:

```
using UnityEngine;
using System.Collections;

public class BrickLife : MonoBehaviour
{
    public int InitialLife = 1;
    private const int MaxLife = 5;
    private static Color[] colors =
       new Color[MaxLife] { Color.red, Color.green, Color.blue, Color.yellow, Color.cyan };

    void Start()
    {
       if (InitialLife == -1) //-1 is indestructible
          GetComponent<MeshRenderer>().material.color = Color.gray;
       else
       {
          InitialLife = Mathf.Clamp(InitialLife, 1, MaxLife);
          UpdateColor();
       }
    }
    void Update() { }
    void UpdateColor()
    {
       GetComponent<MeshRenderer>().material.color = colors[InitialLife - 1];
    }
    void OnCollisionEnter(Collision collision) //When ball hits
    {
       if (InitialLife > 0) //Don't hurt/kill indestructible blocks
           if (--InitialLife == 0) //Hurt the block
               Destroy(gameObject); //If it's dead
           else
               UpdateColor(); //If it's not dead
    }
}

```

`Physics` handles the physics, `Renderer` handles rendering, `BrickLife` handles brick state/existence.
> 1 votes

# Answer
From my experience, there is only a certain level of abstraction you can do before it becomes overdone. It also depends on whether you are using a game engine that intends you to do it that way or not. Unity for one splits up into Update, FixedUpdate and LateUpdate, each with its own intended use.

Regardless, if you are trying to split code into renderer and logic, one would require 2 classes. A logic class and a renderer class. A logic class will send render events to the renderer class and the renderer just do as it is told.

From what I can see in your code, this is all logic code. How I would suggest doing it using the above architecture is (in pseudocode),

```
Logic.Destroy() {
    Renderer.PlayDestroyedAnimation();
}
Renderer.PlayDestroyedAnimation() {
    start countdown
    if (countdown < 0) Logic.DestroyedAnimationFinished();
}
Logic.DestroyedAnimationFinished() {
    life--;
}

```
> 4 votes

# Answer
If you look at the MVC pattern (Model, View, Controller) the answer really becomes clear. The model is your data, the view is the rendered representation of your data. By convention in MVC, your view knows ideally nothing about your model and vice versa. That's where the controller comes in.

The controller is responsible for communication between the model and view. If the user interacts with the view, the message is sent to the controller. If the model needs to be updated from that user interaction the controller passes the model the necessary info and gets back what it needs to update the view (render it again).

It is certainly possible to write games with MVC however most popular gaming frameworks don't use traditional MVC. Instead you'll see the concept again and again of Sprites, Containers and `object.update()` functions. In this case your view respresentation exists within your models (sprites and containers) and receives events and data with each call to `object.update()`. Another common idea is that once a sprite is added to a container it becomes "live" and then automatically begins receiving update messages. In this architecture rendering happens completely behind the scenes and is loosely coupled with your data.

For example:

1. You create 100 enemy sprites
2. You add them to the game container
3. In adding them to the game container the game loop begins rendering each sprite on every update loop
4. Player destroys a few enemies
5. Enemy sprites remove themselves from the container on death
6. Update loop no longer renders those sprites because they are removed from the container

As you can see from the above, at no point are the enemy sprites (your data) concerned with rendering themselves.
> 3 votes

# Answer
Game logic and visual representation should be as decoupled as possible. One method is to use an event system. This allows each portion of game logic and each portion of the visual representation to register for events that they care about.

Consider the following psuedo code of your situation.

```
GameLogic.Register("OnBlockHit", function(...)
{
  FireEvent("OnBeginDestructionCountdown", 10.0);
});

GameLogic.Register("OnBlockDestroyed", function(...)
{
  this.life -= 1;
});

Block.Register("OnBeginDestructionCountdown", function(countdown)
{
  this.dCountdown = countdown;
  this.PlayDestructionAnimation();
});

Block.Register("OnEndDestructionCountdown", function(...)
{
  this.destroy();
  FireEvent("OnBlockDestroyed");
});

// update function
function()
{
  if (this.dCountdown > 0) {
    --this.dCountdown;
    if (this.dCountdown <= 0) {
      FireEvent("OnEndDestructionCountdown");
    }
}

```
> 1 votes

---
Tags: javascript, architecture
---


# Question
Title: Calculate values in a game, which depends from stats and balance them
So, I am basically lost at this point, trying to balance things.

In design phase; I did assign certain values to stats (imagine a standard set of any RPG you ever playe, to make things streamlined).

Now, I would like to start to introduce variants that does not depend directly on a stat; a good example could be "fatigue".

In my system, I have the value for strenght, and energy. Strength is constant (it may grow, but for the calculation purpose it is the constant part), so if I want to calculate fatigue:

```
strenght (0-99) constant
energy (0-99)
fatigue = [(strenght / energy)*10]

```

Easy...but when I plug in numbers, hell break loose.

Imagine that the character has a strenght of 100, start at 100 with energy, and each x steps, energy diminish, increasing his fatigue.

```
Strenght = 100
energy = 100; fatigue = (100/100)*10 = 10
energy = 90; fatigue = (100/90)*10 = 11,1
energy = 80; fatigue = (100/80)*10 = 12,5
energy = 40; fatigue = (100/40)*10 = 25
energy = 20; fatigue = (100/20)*10 = 50

```

This would work like a charm, maxing at 100 when energy is at 10%; but if the character has lower strenght, say 15, I end up with values as above, that are as following

```
Strenght = 15

1.1
1.6
1.8
3.7
7.5
15

```

This means that I don't get even close to 100 for fatigue, when energy is at 10% (I am at 15). So I am actually not sure how do you create formulas for parameters interaction in a game? The more complex I make it, the greater is the variance among the results; while Ideally I am aiming at having the character to take longer to reach 100 fatigue, if his strenght is higher, while it should reach fastr the limit, if the strenght is slower.

But in any case; when the energy reach 10%, the fatigue should be equivalent to 100.

Any suggestion wouold be appreciated; spending too much time on this, which should be pretty straight forward.

# Answer
If you want your characters to last longer as they grow up their strength, I would suggest you to make a different approach about the energy parameter. Maybe you would want to max the energy to the current strength value, so your characters will have more energy to spend with higher strength values.

Something like:

```
Strength = [1, N]
Energy = [0, Strength]

```

This has the advantage of not having to calculate the energy cost of many actions and it can be a discrete value. This way you can also calculate the discrete fatigue and the fatigue coefficient.

```
dFatigue = Strength - Energy
cFatigue = (Strength - Energy) / Strength

```

With the fatigue coefficient you will have a `[0, 1]` value to play with. If you want a linear fatigue progression you can multiply the coefficient by 100, or you can make some other calculations to make different progressions.

```
linearFatigue = cFatigue * 100
exponentialFatigue = (cFatigue ^ 2) * 100 // Slow progression with high energy, fast progression with low energy
rootFatigue = sqrt(cFatigue) * 100 // Fast progression with high energy, low progression with low energy

```

You can test whichever equation in an online math function graph plotter to test your ranges. These three equations will give you a `[0, 100]` value for fatigue with different basic progressions.
> 1 votes

# Answer
I would suggest a "negative" of `e^0.5 * s ^ 0.5` function:

```
//strength and energy belongs to <0,100>
fatigue = 100 - Math.sqrt(strength) * Math.sqrt(energy)

```

it gives you smooth progression with a diminishing returns for near full gear and 100 value near `energy = 0` (you can offest it). One downside of this, it will now behave similarly for `strength -> 0` so be sure there is a minimal strength first (again, you can just offset it).
To get better idea about shape of the e^0.5 * s ^ 0.5 function you can, for example, visit wolframalpha (or to "test" any other function!).
> 1 votes

---
Tags: mathematics, game-design
---


title: OpenGL strange color issue

text:
# Question
Title: OpenGL strange color issue
I recently made terrain generation for my game, and I created a lighting system (simply diffuse lignting), but there's a strange problem around the edges.

I know, OpenGL interpolates the different values between the vertex shader and fragment shader, but in this case, it comes out strangely. Here is the issue:

The edges of the squares look a little jagged (I use triangles).

I especially don't understand this one:

Every vertex of that area is dark, but the middle is lighter.

Here are the codes for the vertex and fragment shader:

Vertex shader:

```
#version 330 core

in vec3 vertex;
in vec3 normal;
in vec4 color;

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;

out vec3 vertexNormal;
out vec3 cameraPos;
out vec3 vert;
out vec4 vertColor;

void main() {
    gl_Position = projection * view * model * vec4(vertex, 1.0);
    vertexNormal = normal;
    cameraPos = vec3(view[3][0], view[3][1], view[3][2]);
    vert = vertex;
    vertColor = color;
}

```

Fragment shader:

```
#version 330 core

in vec3 vertexNormal;
in vec3 cameraPos;
in vec3 vert;
in vec4 vertColor;

uniform vec3 sunColor;
uniform vec3 sunDirection;

void main() {
    vec3 toLightVector = -sunDirection;
    vec3 uLightVector = normalize(toLightVector);

    float diffuse = max(dot(uLightVector, vertexNormal), 0.1);
    vec3 lightColor = diffuse * sunColor;

    gl_FragColor = vec4(lightColor, 1.0) * vertColor;
}

```

# Answer
What you are rendering is correct linear interpolation of your lighting values. The odd highlighting of the edges and the darkening on others is, like Lorenzo pointed out, an optical illusion. I recommend you zoom in on the second image and look closely at how those color values are being interpolated along those points. Although it looks a little wonky further out, up close it all clearly follows the rules you think it should.

There are various methods you could use to change how this looks out. The simplest of which is to increase the resolution of your geometry, which provides more polys over which your lighting can interpolate. Another option might be to implement a more complicated lighting calculation, enabling you to map a more appealing curve to the interpolation.

Apologies if this is at all confusing, I'm just a computer graphics hobbyist who enjoys playing with rendering technologies.
> 3 votes

# Answer
The lighter middle is an optical illusion. Vertex colors appear a bit random (the geometry is too coarse and/or the lighting is approximate), but fragments are interpolated linearly as they should.
> 1 votes

---
Tags: opengl, glsl, lighting
---


# Question
Title: How to handle two players playing on one keyboard with Box2D (LibGDX)?
I'm making a racing game with LibGDX and Box2D. I've been using this tutorial to implement the basic physics, and it works properly.

My **main problem** is to implement two different sets of keys (*UP-DOWN-LEFT-RIGHT* and *ASDW*) to control two different instances of a Car class on a same screen.

The code I have yet for handling one set of input (for KeyDown):

```
@Override
public boolean keyDown(int keycode) {
    if (keycode == Input.Keys.UP) {
        if (!pressedKeys.contains(Key.Up)) {
            pressedKeys.add(Key.Up);
        }
    } else if (keycode == Input.Keys.DOWN) {
        if (!pressedKeys.contains(Key.Down)) {
            pressedKeys.add(Key.Down);
        }
    } else if (keycode == Input.Keys.LEFT) {
        if (!pressedKeys.contains(Key.Left)) {
            pressedKeys.add(Key.Left);
        }
    } else if (keycode == Input.Keys.RIGHT) {
        if (!pressedKeys.contains(Key.Right)) {
            pressedKeys.add(Key.Right);
        }
    }
    return false;
}

```

(KeyUp):

```
    @Override
public boolean keyUp(int keycode) {
    if (keycode == Input.Keys.UP) {
        if (pressedKeys.contains(Key.Up)) {
            pressedKeys.remove(Key.Up);
        }
    } else if (keycode == Input.Keys.DOWN) {
        if (pressedKeys.contains(Key.Down)) {
            pressedKeys.remove(Key.Down);
        }
    } else if (keycode == Input.Keys.LEFT) {
        if (pressedKeys.contains(Key.Left)) {
            pressedKeys.remove(Key.Left);
        }
    } else if (keycode == Input.Keys.RIGHT) {
        if (pressedKeys.contains(Key.Right)) {
            pressedKeys.remove(Key.Right);
        }
    }

    return false;
}

```

How should I do to be able to handle *UP-DOWN-LEFT-RIGHT* and *ASDW* keys simultaneously?

Note: A Car is instantiated in the main class.

**I can always add more code if needed.**

# Answer
It's a little unclear what you are trying to accomplish with your pressed keys object, but here's a suggestion.

Create a car controller class which takes a car as a parameter in its constructor. And has several action objects that you can bind to. Here's an example for the accelerator (I haven't compiled this so it may need some tweaking)

```
public class CarController{
    public ICallable<Void> pushAccelerator;
    public ICallable<Void> releaseAccelerator;
    public CarController(final Car car)
    {
       pushAccelerator = new ICallable<Void>(){
           public Void call(){
               car.pushAccelerator();
               return null;
           }
       }
       releaseAccelerator = new ICallable<Void>(){
           public Void call(){
               car.releaseAccelerator();
               return null;
           }
       }
    }
}

```

Then in your input handler you could have two mappings, one when the key is pressed, one when the key is released.

```
private Map<Integer,ICallable<Void>> keyPressedHandlers = new HashMap<Integer,ICallable<Void>>();
private Map<Integer,ICallable<Void>> keyUpHandlers = new HashMap<Integer,ICallable<Void>>();

public void mapInputs(Car car1, Car car2){
   CarController controller1 = new CarController(car1);
   CarController controller2 = new CarController(car2);
   keyPressedHandlers.put(Keys.W,controller1.pushAccelerator);
   keyPressedHandlers.put(Keys.UP,controller2.pushAccelerator);
   keyUpHandlers.put(Keys.W,controller1.releaseAccelerator);
   keyUpHandlers.put(Keys.UP,controller2.releaseAccelerator);
}

public boolean keyDown(int keycode) {
    if(keyPressedHandlers.containsKey(keycode)){
        keyPressedHandlers.get(keycode).call();
    }
 }

 public boolean keyUp(int keycode) {
    if(keyUpHandlers.containsKey(keycode)){
        keyUpHandlers.get(keycode).call();
    }
 }

```

This sort of mapping approach even makes it so you could eventually allow a user to map their own keys to the car's actions.
> 1 votes

---
Tags: java, libgdx, box2d, multiplayer, keyboard
---


title: how to port my game for android in sfml

text:
# Question
Title: how to port my game for android in sfml
i am a c++ programmer , and I want to develop games . I chose sfml , because I wanted to see what happens behind the scene better . I have an idea to make , and the desired platform is mobile devices(android , ios) . I have seen that sfml , support for touch and other capabilities of mobile devices , but I have no idea , how I can write a code , that works on all of them .

# Answer
> 4 votes
SFML still does not officially support Android development as you can see on their official website (http://www.sfml-dev.org/index.php).

> With SFML, your application can compile and run out of the box on the most common operating systems: Windows, Linux, Mac OS X and **soon Android & iOS**.

However, there is a recently updated tutorial on how to build SFML for Android on Github: https://github.com/SFML/SFML/wiki/Tutorial:-Building-SFML-for-Android. But since Android is not officially supported you will probably run into many problems.

---
Tags: android, sfml
---


# Question
Title: InvalidOperationException when peeking from a stack within custom editor
I've got a simple state machine for handling game states which works using `GameObject`s that I enable/disable in order to switch the states. Since some states can be loaded additively (such as the pause menu), I'm using a stack to manage the currently active ones.

```
public class GameController : MonoBehavior {

    private readonly Stack<GameObject> _stateStack = new Stack<GameObject>();

    public GameObject ActiveState {
        get { return _stateStack.Peek(); }
    }

    public void SetState(GameObject newState, bool isAdditive = false) {
        if(newState = null || newState == ActiveState)
            return;

        if(!isAdditive) {
            while(_stateStack.Count > 0)
                PopState();
        }

        if(!newState.activeInHierarchy)
            newState.SetActive(true);

        _stateStack.Push(newState);
    }

    public void PopState() {
        var gameState = _statStack.Pop();
        if(gameState != null)
            gameState.SetActive(false);
    }

}

```

Now I'd like to have a custom editor which allows me to see and set the currently top-most active state.

What I did was this:

```
[CustomEditor(typeof(GameController))]
public class GameControllerEditor : Editor {

    public override void OnInspectorGUI() {
        DrawDefaultInspector();

        var controller = target as GameController;
        if(controller == null)
            return;

        var newState = EditorGUILayout.ObjectField("ActiveState", controller.ActiveState,
              typeof (GameObject), true) as GameObject;
        if (newState != controller.ActiveState)
            controller.SetState(newState);
    }

}

```

However, the custom editor is never visible and in the console, I see the following exception:

```
InvalidOperationException: Operation is not valid due to the current state of the object
System.Collections.Generic.Stack'1[UnityEngine.GameObject].Peek()

```

What does this even mean? What state? Is the stack not initialized? How does Unity instantiate `MonoBehavior`s when applying a custom inspector?

# Answer
> 1 votes
Peek throws an exception if the Stack is empty, so you will need to check wherever appropriate that Count \> 0 beforehand, or use try/catch if that matches your intent better.

---
Tags: c#, state, game-state, unity
---


# Question
Title: Stencil buffer appears to not be decrementing values correctly
I'm attempting to use the stencil buffer as a clipper for my UI system, but I'm having trouble debugging a problem I'm running in to.

This is what I'm doing: A widget can pass a rectangle to the the stencil clipper functions, which will increment the stencil buffer values that it covers. Then it will draw its children, which will only get drawn in the stencilled area (so that if they extend outside they'll be clipped). After a widget is done drawing its children, it pops that rectangle from the stack and in the process decrements the values in the stencil buffer that it has previously incremented.

The slightly simplified code is below:

```
static void drawStencil(Rect& rect, unsigned int ref)
{
    // Save previous values of the color and depth masks
    GLboolean colorMask[4];
    GLboolean depthMask;
    glGetBooleanv(GL_COLOR_WRITEMASK, colorMask);
    glGetBooleanv(GL_DEPTH_WRITEMASK, &depthMask);

    // Turn off drawing
    glColorMask(0, 0, 0, 0);
    glDepthMask(0);

    // Draw vertices here
    ...

    // Turn everything back on
    glColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
    glDepthMask(depthMask);

    // Only render pixels in areas where the stencil buffer value == ref
    glStencilFunc(GL_EQUAL, ref, 0xFF);
    glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
}

void pushScissor(Rect rect)
{
    // increment things only at the current stencil stack level
    glStencilFunc(GL_ALWAYS, s_scissorStack.size(), 0xFF);
    glStencilOp(GL_INCR, GL_INCR, GL_INCR);

    s_scissorStack.push_back(rect);
    drawStencil(rect, s_ScissorStack.size());
}

void popScissor()
{
    // undo what was done in the previous push,
    // decrement things only at the current stencil stack level
    glStencilFunc(GL_ALWAYS, s_scissorStack.size(), 0xFF);
    glStencilOp(GL_DECR, GL_DECR, GL_DECR);

    Rect rect = s_scissorStack.back();
    s_scissorStack.pop_back();
    drawStencil(rect, s_scissorStack.size());
}

```

And this is how it's being used by the Widgets

```
if (m_clip)
    pushScissor(m_rect);

drawInternal(target, states);
for (auto child : m_children)
    target.draw(*child, states);

if (m_clip)
    popScissor();

```

This is the result of the above code:

There are two things on the screen, a giant test button, and a window with some buttons and text areas on it. The text area scroll box is set to clip its children (so that the text doesn't extend outside the scroll box). The button is drawn after the window and should be on top of it completely. However, for some reason the text area is appearing on top of the button. The only reason I can think of that this would happen is if the stencil values were not getting decremented in the pop, and when it comes time to render the button, since those pixels don't have the right stencil value it doesn't draw over. But I can't figure out whats wrong with my code that would cause that to happen.

# Answer
> 1 votes
For UI purposes you can consider using glScissor. Just enable the scissor before outputting inner elements and disable it afterwards

```
glScissor(x, y, width, height);
glEnable(GL_SCISSOR_TEST);

//draw child elements here

glDisable(GL_SCISSOR_TEST);

```

This will restrict drawing out of specified area. The only note is that this allows only a rectangular scissoring

---
Tags: opengl, stencil
---


# Question
Title: How to make a game object rotate around its Axis in Unity?
Ok So i making this simple platformer with a ball. So basically i have A pickup / Collectible that is a Coin. I want the coin till it gets collected by the ball to keep rotating around it axis . Also I know I could do this by adding a Animation but I would prefer doing it Via A C# Script. So please if anybody knows how then Tell me. Thanks

# Answer
If you are rotating around the x axis, you can use this code:

```
float speed =5f;
void Update () {
        transform.Rotate(Vector3.right *speed * Time.deltaTime);
    }

```
> 1 votes

---
Tags: unity
---


# Question
Title: Unity3d Transfer of value from one script to another
Script 1

```
public class enemy : MonoBehaviour {
    private Vector3 Player;
    private Vector2 PlayerDirection;
    public float Xdif;
    public float Ydif;
    private float speed;
    private float distance;
    private bool stun;
    private float stuntime;
    GameObject playerObj;
    private Rigidbody2D myRigidbody2D;
    private bool isEnemyFear;

    // Use this for initialization
    void Start () {
  stuntime = 0;
  stun = false;
  speed = 6;
  playerObj = GameObject.Find ("Player");
  myRigidbody2D = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    public void Update () {
  distance = Vector2.Distance (Player, transform.position);
  Player = playerObj.transform.position;
  if (stuntime > 0) {
   stuntime -=Time.deltaTime;
  } else {
   stun = false;
  }
  if(isEnemyFear){  //here to pass a value from script 2
   EnemyFear();
  }
  else{
   EnemyAttack();
  }

    }
    void EnemyAttack(){

  if (distance < 25 & !stun) {
   Xdif = Player.x - transform.position.x;
   Ydif = Player.y - transform.position.y;
   PlayerDirection = new Vector2 (Xdif, Ydif);
   myRigidbody2D.AddForce (PlayerDirection.normalized * speed);
   Debug.Log("Attack");
  }
    }

    void EnemyFear(){

  if (distance < 25 & !stun) {
   Xdif = Player.x + transform.position.x;
   Ydif = Player.y + transform.position.y;
   PlayerDirection = new Vector2 (Xdif, Ydif);
   myRigidbody2D.AddForce (PlayerDirection.normalized * speed);
   Debug.Log("Fear");
  }
  StartCoroutine(Timer());
    }

    void OnCollisionEnter2D(Collision2D Playerhit){
  if (Playerhit.gameObject.CompareTag("Player")) {
   stun = true;
   stuntime = 1;
  }
    }
    IEnumerator Timer() {
  yield return new WaitForSeconds(10);
  isEnemyFear = false;
  StopCoroutine ("Timer");
    }

}

```

Script 2

```
public class randomizer : MonoBehaviour {

    private bool isEnemyFear;

    public void CheckFear(){
  int rand = Random.Range(0, 100);
  if(rand > 35)
   isEnemyFear = true; //this value should be passed to the script 1
    }

}

```

How to pass a value `isEnemyFear = true` from Script 2 in Script 1?

# Answer
The variable `isEnemyFear` is declared as `private` in both scripts which means it is not exposed to other scripts and can not be read or set by them.

But if you would declare is as `public` and when you have both scripts on the same game object, you could set it from one script in the other by getting that script with `GetComponent`. So you could either have the `randomizer` component modify the data of the `enemy` component with

```
 GetComponent<enemy>().isEnemyFear = true;

```

or have the `enemy` component pull the data from the `randomizer` with

```
if (GetComponent<randomizer>().isEnemyFear) {

```

Note that in both cases it is very likely redundant to have that variable in both components.

When these two components are on different game objects, you first need a reference to the other one, so you can use `otherGameObject.GetComponent`. There are different ways to do that, like having a variable for it which you set in the inspector, using `GameObject.Find("name")` (warning: slow) or when one game object instantiates the other, retaining the reference. Which one you should use depends on how your project is structured.
> 1 votes

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


# Question
Title: Get water flow direction vector from water normal vector
Im stuck developing an important detail of my game water: Making it flow downwards!

Considering a typical 3D world in wich water tends to go towards gravity `g=(0,-1,0)` , and having the normal of the water surface `n=(x,y,z)`, how can I calculate, based on that, the water flow direction vector?

As an example, consider this badly-done graph (In 2D, though)

Update: I'm considering a **very simplified** water surface (Just a plane: No ripples, no waves, no pressure, etc.). If any of those needed to be applied, the answer would depend on more factors than just the normal.

# Answer
One way to do it, considering you want a 90° angle, is to find the cross product of the normal and gravity, normalize it, then cross that with the normal again.

In your diagram, the first cross will produce a vector pointing into the screen, and the second cross will produce the flow vector.

An interesting side-affect of using cross products is that the flow vector will be longer the further the normal vector is away from vertical, which could be used for flow speed?

This assumes you are using a right-handed coordinate system, if your system is left hand, the intermediate vector will point out of the screen instead, but will still produce the same result.
> 13 votes

# Answer
You cannot determine the direction of flow of water from its surface normals, you will need to store additional data.

A simple trip to look at a river should be sufficient to convince you of this. Any difference in the surface normals merely reflects rippling in the surface, the mass of water continues to flow in the same direction. But the underlying reason is because the normal defines a *plane* and you need a *vector* of flow. Your vectors are about the shape of the surface not the movement of the water.
> 1 votes

---
Tags: 3d, mathematics, geometry
---


# Question
Title: AS3 Air - Custom slider - limit drag position
I'm facing issues with finding the right solution for detecting and limiting the Sprite object "Knob" moved on y axis inside it's parent sprite "Frame", using FlashDevelop 5.

Using the code bellow I'm creating the frame on stage

```
private function init():void{
var frame: Frame = new Frame;
frame.x = 100;
frame.y = 100;
addChild(frame);
}

```

And in the Frame class, I create the child named "Knob" and add touch event listeners (with multitouch support, therefore using dictionary - Thanks to this post ):

```
public class Frame extends Sprite
    {
        public var knob: Knob;
        private var curTouchPoints:Dictionary = new Dictionary();

        public function Frame()
        {
            addEventListener(Event.ADDED_TO_STAGE, addListeners);
            init();
        }

        private function addListeners(event:Event):void
        {
            stage.addEventListener(TouchEvent.TOUCH_MOVE, touchMove);
        }

        private function touchStart(e:TouchEvent):void
        {
        curTouchPoints[e.touchPointID] = {obj: e.currentTarget, offsetX: e.localX, offsetY: e.localY}; //store the current object in the dictionary
        trace(e.currentTarget)
        e.currentTarget.addEventListener(TouchEvent.TOUCH_END,touchEnd);
        }

        private function touchMove(e:TouchEvent):void
        {
          if (curTouchPoints[e.touchPointID]) {
          DisplayObject(curTouchPoints[e.touchPointID].obj).y = e.stageY-this.y - curTouchPoints[e.touchPointID].offsetY;
        }
        }

        private function touchEnd(e:TouchEvent):void
        {
        delete curTouchPoints[e.touchPointID];
        e.currentTarget.removeEventListener(TouchEvent.TOUCH_END, touchEnd);
        }

        private function init():void
        {
            this.graphics.beginFill(0xffffff, 1);
            this.graphics.lineStyle(1, 0x000000, 1);
            this.graphics.drawRect(0, 0, 120, 600);
            this.graphics.endFill();

            knob = new Knob;
            knob.x = 20;
            knob.y = 20;
            knob.addEventListener(TouchEvent.TOUCH_BEGIN, touchStart);
            addChild(knob);
        }

    }

```

The Knob class is simple sprite object:

```
public function FaderKnob()
        {
            this.graphics.beginFill(0x000000, 1);
            this.graphics.lineStyle(1, 0x000000, 1);
            this.graphics.drawRect(0, 0, 80, 80);
            this.graphics.endFill();
        }

```

With the current code, it all works as expected except that I want to limit the Knob to never leave it's parent - Frame! Means, it's top coordinate will be 0, and it's bottom should be `"Frame.heigth - Knob.height"`, so it stays fully inside.

I've been searching for the HitTestObject, but that doesn't do the work as the Knob is in the Frame all the time... :/

If it matters: The window is/will be transparent with chroma:none, and both, frame and knob should have alpha 0 (whole app is supposed to be fully transparent, to implement multitouch support on non-multitouch game) This is done fine now, just mentioning if it might matter for some HitTest procedures based on pixels or something.. I'm fairly new to AS3 and Air so please bare with me :-)

As a side note, I'd need to read the 8-bit "value" (0-255) based on the knob's position in its parent, which I have a slight idea of how to do, but I'm sure there's an easier way than what I imagined.. :)

# Answer
This should be a pretty straight-forward task:

So let's say you have a handle at position `hX, hY`, and you have a drag event that you have verified started on the handle at `sX, sY` and ended at `eX, eY`. To add vertical scrolling, you would change the handle's y position like so: `hY += (eY - sY);`. Now, to stop the handle from going out of bounds, you would need to clamp that result to the given range, for an example like `hY = clamp(hY, topMostPosition, topMostPosition + areaHeight - handleHeight);`.
> 1 votes

---
Tags: actionscript-3, flashdevelop, flash-develop
---


title: Circle to Polygon collision response

text:
# Question
Title: Circle to Polygon collision response
I'm working for collision response for my 2d game. Character is represented by circle and obstacles are represented by Polygons(in my example it would be rotated rectangle for simlification). The problem is when circle collides with vertice of polygon, I know how it must work , but can't find the vector.
C - the center of the circle.
V - vertice.
P - the center of the polygon.
X - the vector I need to find.
Then I'll just move my character by vector V.sub(X).
Tried this algorithm, but it gained no result.
https://stackoverflow.com/questions/1073336/circle-line-segment-collision-detection-algorithm

# Answer
> 1 votes
Detecting a collision between a circle and a line is relatively simple, just write an equasion for all the point on the circle as implicit equasion:

```
(x-4)^2 + (y-6)^2 = R^2

```

Where `R` is your diameter, then write equation for the line using a parameter:

```
x = t * 5 + (1-t) * 8   // t * V[x] + (1-t) * P[x]
y = t * 5 + (1-t) * 5   // t * V[y] + (1-t) * P[Y]

```

And substitue into previous equation, giving you a single quadratic equation with one variable `t`. I reccoment solving this by hand at first, and then rewrite the same process into code.

Also this intersects whole line with your circle, not just a line segment, so just only accept solutions where `t` is in range `[0,1]`.

# Answer
> 0 votes
The solution is simple as that:

P = Circle center r = radius or the circle

* You get the closest point from the circle center to the polygon (C) (I assume you got that already)
* Get the distance from the closest point to the circle center (D) = C-P
* Normalize that distance to get the unit vector (N)
* Get the signed distance to the edge/vertex and take the radius into account (s) = r - (N dot D)
* Multiply your unit vector by the signed distance and you get the minimum translation vector (MTV) = N * s
* Use MTV to resolve collisions, either by applying a impulse or by directly correcting the position (Depends on the result you want)
* Done

---
Tags: java, 2d, collision-detection, libgdx
---


# Question
Title: Create YUV texture for GL_TEXTURE_EXTERNAL_OES format
0 down vote favorite

I need to create a yuv texture for GL\_TEXTURE\_EXTERNAL\_OES format.

source : https://github.com/crossle/MediaPlayerSurface/blob/master/src/me/crossle/demo/surfacetexture/VideoSurfaceView.java

I am doing all processing on YUV, so it would save clock cycles, if I can generate a yuv texture as output of texture2D.

To get 'y' value, I need to take dotproduct of each texel with vec3 of (0.3,0.59,0.11) Since, for my purpose I need to take 3x3 pixel block's 'y' value and take a convolution of them, this results in performance impact. So it would save clock cycles, if I can generate a yuv texture as output of texture2D.

# Answer
> 0 votes
sam hocevar, in a comment above, recommends making use of hardware blinear filtering like this pseudocode:

```
sample = (vec4)0;

sample += tex2D(sourceTexture, sourceTexelUV + (1/2 texel stride) * (-1, -1));
sample += tex2D(sourceTexture, sourceTexelUV + (1/2 texel stride) * ( 1, -1));
sample += tex2D(sourceTexture, sourceTexelUV + (1/2 texel stride) * (-1,  1));
sample += tex2D(sourceTexture, sourceTexelUV + (1/2 texel stride) * ( 1,  1));

float blurredLuminance = dot(sample, luminanceCoefficients/4f);

```

(I've also seen this implemented where we compute U and V ± 1/2 texel stride in the vertex shader, and pass those four values to the fragment shader rather than computing this constant offset per-fragment)

How are we getting a 3x3 kernel with only 4 samples? Each sample is exactly at the corner between 4 texels, so with the texture filtering mode set to bilinear we'll get an average of all 4 texels returned to us very efficiently, since sampling & blending of each texel is implemented in the hardware.

Summing all these pre-blended samples, the math works out that we get a final blend that's 1 part from each corner, 2 parts from each cardinal neighbour, and 4 parts from the center texel - exactly the relative weights we want from a 3x3 Gaussian blur.

Since the dot product is linear, we can do it once on the accumulated result, dividing by the number of samples at the same time (this can be combined into one constant).

I agree with sam that this is probably faster than my 2-pass suggestion. I'd forgotten that separating Gaussians into 2 passes is mainly an efficiency for larger filter kernels, and for a 3x3 kernel it would actually result in more texture sampling workload than the single-pass version outlined here.

---
Tags: opengl, shaders, textures
---


title: CryEngine with Visual Studio 2015

text:
# Question
Title: CryEngine with Visual Studio 2015
I receive an error in Visual Studio when I open CESharpFramework from my project folder. I had assumed I could use Visual Studio 2015; but the error tells me I need an older version of Visual Studio to open the MonoLauncher solution within CESharpFramework.

Is this a known issue and what should I do?

# Answer
Make sure you installed GTK# and MonoDevelop. I use CE5 with Visual Studio 2015 but not with C# but the docs said something about that. I suggest you reffer to this document, it should fix your issues. Have you installed VS2015 with Xamarin support?
> 1 votes

---
Tags: visual-studio, cryengine
---


title: Open CryEngine console from lua script

text:
# Question
Title: Open CryEngine console from lua script
Is there a function in the CryEngine Lua API to open the `~` Console? I cannot find it in the Lua (`ScriptBind`) API reference.

# Answer
> 1 votes
Do you mean to open the console by lua script or execute a console command from lua? As far as that goes, it would be hell of a workaround to run console commands by lua. It would be much easier to expose the c++ function that does the things you want (for example the function which the console command calls) to the lua engine and run it directly (refer to this).

Just in case you want to invoke lua from the console, simply run your script from the console by putting a # in front of it (This only works in Sandbox or when launching with -DEVMODE).

---
Tags: lua, cryengine
---


# Question
Title: What to consider when deciding on 2D vs 3D for a game?
How much "harder" is 3D than 2D in terms of:

* Amount/complexity of the code
* Level of math skills required
* Time involved in making art assets

*Original title: How hard is 3D game development versus 2D?*

# Answer
3D is an order of magnitude harder than 2D:

**Programming:**

* **The math is significantly more complex** for rendering, physics, collision, etc. Hope you like matrices and vectors!
* Because of the previous point, **good performance is much more difficult to attain**. With today's hardware, you can make a nice-looking 2D game without having to think about performance at all beyond not being actively stupid. With 3D, you will have to do some optimization.
* **The data structures are much more complex.** Because of the previous point, you'll need to think about culling, space partitioning, etc. all of which are more challenging then a simple "here's a list of everything in the level".
* **Animation is much more complicated.** Animation in 2D is just a filmstrip of frames with possibly different positions for each frame. With 3D, you'll need to deal with separate animation assets, bones, skinning, etc.
* **The volume of data is much higher.** You'll have to do intelligent resource management. Games ship with gigs of content, but consoles sure as hell don't have gigs of memory.
* **The pipelines are more complex to develop and maintain.** You'll need code to get assets into your engine's preferred format. That code doesn't write itself.

**Art:**

* **The assets are, of course, much more complex.** You'll need textures, models, rigs/skeletons, animation, etc. The tools are much more complex and expensive, and the skills to use them harder to find.
* **The set of skills needed is wider.** Good animators aren't often good texture artists. Good lighters may not be good riggers.
* **The dependencies between the assets are more complex.** With 2D, you can partition your assets across different artists cleanly: this guy does level one, this guy does enemies, etc. With 3D, the animation affects the rig which affects the skeleton which affects the model which affects the textures which affect the lighting... Your art team will have to coordinate carefully and constantly.
* **The technical limitations are more complex to deal with.** With 2D it's basically "here's your palette and your max sprite size". With 3D, your artists will have to balance texture size (for multiple textures: specular, color, normal, etc.), polygon count, keyframe count, bone count, etc. The particulars of the engine will place random weird requirements on them ("Engine X blows up if you have more than 23 bones!").
* **Asset processing takes longer.** Pipelines to convert 3D assets to game-ready format are complex, slow, and often buggy. This makes it take much longer for artists to see their changes in game, which slows them down.

**Design:**

* **User input is bitch.** You have to deal with camera tracking, converting user input into the character's space intuitively, projecting 2D selections into world space, etc.
* **Levels are hard to author.** Your level designers basically need the skills of a game designer and an architect. They have to take into account players getting lost, visibility, etc. when building levels.
* **Level physics is tedious to author.** You'll have to check and recheck and recheck again to make sure there aren't gaps and bugs in the level physics where players can get stuck or fall through the world.
* **Tools are much harder.** Most games need their own tools for authoring things like levels. Since the content is so much more complex, the tools are more work to create. That usually results in tools that are buggier, incomplete, and harder to use.
> 127 votes

# Answer
Lots harder. If you're not comfortable making a 2D game, you will REALLY not like what it takes to make a 3D game.

The good news: 99% of the time, you don't really need it. Think of any 3D game you can. Take the camera, fix it on the ceiling looking down so that you're now looking at a 2D plane. Doom becomes Gauntlet. Civ IV becomes Civ I. Metal Gear Solid becomes the original Metal Gear. None of these games are "bad" just because they're 2D; they are perfectly playable and generally have much of the same gameplay.
> 11 votes

# Answer
Largely, 3D is going to introduce more difficulties than simplifications. But I just feel like adding a few things that might actually be easier in a 3D game:

* Player customizations. Imagine if Team Fortress 2 were a 2D platformer with 20 animations for each class. Now, imagine your marketing director has suggested you add hats to the game. This would mean 20 new spritesheets for every class; and it would only expand if you decide to add other miscellaneous items. One company I worked for ran into this frustration.
* Character movements. Rigging and animating is definitely not a simple task, but if your characters are complex, then it's eventually going to be an easier job than in 2D, where you'd be redrawing the character completely for each pose. Practically the first mark of excellence in any 2D game is how many times the creators were willing to redraw their characters for additional animation.
* Finding an engine. I can make a simple platformer in less than one hour in 3D with no coding at all, but it might take a bit longer in 2D. You'll definitely find plenty of good 2D engines out there after some looking, but honestly nothing immediately comes to mind for me; few have hit their massive popularity the way Ogre3D or other 3D engines have. For 3D, there's UDK, Unity, and far more frameworks available. Part of this might be that the reduced complexity of 2D means that it's not so difficult for amateurs to just write their own, basing off of XNA. (Plus, some of the mentioned 3D engines can be made viable to create a 2D game)
> 7 votes

# Answer
This is a highly subjective question, since the answer depends on personal preference/experience/knowledge/intelligence.

I will try to answer neutrally, but since I am only a programmer and not an artist i can only hypothesize for the last point.

Code complexity should not be so very different, except in maths and maybe rendering/physics. Game Logic isn't so much different if you take a healthy level of abstraction (not too much - you're trying to make a game not an engine, at least I guess from your question.) Obviously its a lot easier to calculate movement in 2D because you have limited perspective. Physics is WAY more difficult when dealing in three axes. Also, loading a Sprite from a Bitmap is a lot easier than loading a 3D Model (and possibly texturing).

Maths is more complicated for 3D (a no-brainer really - quaternions, vectors, matrices. 'nuff said)

For art, I think it must be more difficult for 3D too, since you need to create art that looks good from every possible viewing angle (or at least a wide range), and you usually want to texture things too. Animating a mesh is no picnic to get realistic, and getting the texture to play along isn't either.
> 3 votes

# Answer
The other thing to consider ... with a 3D game you probably want to consider using a pre-existing engine and concentrate on making a game not an engine. It can go someway to reducing the time and difficulty taken in a 3D game (as excellently identified by munificent).

It's much easier to build a 2D game ground up. But obviously you can (and should consider) using sprite, sound, portability libraries as well. No point in reinventing the wheel except for education purposes.

Seems obvious - but I thought it was worth saying.
> 3 votes

# Answer
Allow me to offer one interesting consideration for mobile devices where 2D performance can actually lag behind low poly 3d models:

1) Fill rate can cause quite a bit of performance trouble when dealing with many sprites on screen at a given time.

2) Texture memory requirements for a fully fleshed out 2D game are actually much higher if you're using frame based animation. Each and every single character frame blows out your total texture budget in a linear way. This means that if you use simple flipbook animation you actually have a more constricted animation budget than you would with skeleton based 3D animation.

Toolkits like Spine help level this playing field a bit by creating 2d deformations of a texture.

---

So, considering this, and the ease of access of Unity and UDK which both extract much of the complexity of game development that existed years ago for 3D, the answer is not so straight forward.
> 2 votes

# Answer
It depends on game developer. The time consuming part is making game assets. If you feel it is easier for you to make these assets with illustrator and Photoshop then 2D is easier for you, but if you know 3D modeling probably you agree with me that 3D is much easier than 2D.

Regarding animation, definitely 3D is easier and faster and easier to manage.

For example while in 3D you can make all of animations for a character in a few hours in one scene, in 2d you have to draw the character from scratch for any activity he is suppose to do and save many files, it takes days in 2D vs. hours in 3D.

Also if you change something, you have to redo it all in 2D, but you don't have to change everything for example if you decide your character should not have a hat. You don't have to redo all the animation you just delete the hat in 3D.

If you have humanoid characters, there are Thousands of free mo-cap animations. Most of the time you don't need to make any animation for your game.

Regarding complexity and programming there is no difference.

But you should know 3D well, otherwise you may end up in game engine your animation is different from your 3D app or your character head is rotating in reverse direction and you don't know how to solve the problem, and some other glitches.

Also you should be familiar with low poly modeling for game and how to do texturing for game, it is different from modeling and texturing for animation.

By the way Contrary to popular belief 3D is less hardware demanding for mobile devices .
> 1 votes

---
Tags: 2d, 3d
---


# Question
Title: RPG Data (Skills, Monsters, Items, Equippables)
I'm creating a simple RPG type game. I've dabbled with the idea of just loading all the skills, monsters, items and so on at once. However, to do that seems horrible wasteful since I would have potentially hundreds of things in memory that may not necessarily be used just for the battle system.

I'm pretty close to finishing the battle system, I just need to figure out how to handle the data prior.

So would it be best just to just access the disk to load this information in when I need it? I was considering porting this to another device after I get it working on a PC.

I was looking at the decompilation of Pokemon Red and I'm not exactly sure how they managed to do it either. Given that the RAM for the Gameboy was 8 kilobytes (32 if expanded).

Any pointers (no pun intended) or ideas?

# Answer
> 2 votes
*Hundreds* of items is really not much for today's hardware. The mechanics-relevant information about items, enemies etc. is likely not going to be more than a few hundred bytes per entity. So keeping it all in memory is likely not that much of an issue.

What could become an issue is sprites and sounds. A decompressed spritesheet or sound file can easily eat up a few megabyte which can be problematic on low-end mobile devices. A simple solution for this is to request any such resources through a resource cache. Whenever the resource is needed, request it from the cache. The cache checks if that resource is in memory, and if not loads it from disk. It also checks in regular intervals which resources were not requested for x seconds and discards them. The only thing you need to keep in mind is that you *always* request resources through the cache and don't maintain any other references to it. This is required to make sure the cache is aware of any use of the resource.

A more precise but harder to maintain option is to explicitly load sprites and sounds when they are needed and explicitly unload them when they are not. For example, when you enter a battle, you check who participates in the battle and load all their sprites. When the battle is over, you explicitly release those sprites from memory. This would be the best strategy to minimize memory footprint, but also the one where you are most likely to end up with missingno-like bugs due to accidentally using sprites which aren't loaded or after they are released.

# Answer
> 1 votes
Disk access, I mean I/O time, is another resource to worry about.

It's OK to worry about unneeded memory usage, having cellphones with 1 to 3 GB or RAM or computers with 4 - 8+ GB or RAM is no excuse to not do things in the most optimal possible way. But use a bit more RAM to avoid slow I/O, or to concentrate most of the I/O in specific parts of the game like at the start of the level, is a perfectly valid excuse and one used by games since the first day.

I don't know how your structures look but hundreds of items cannot be so RAM filling. I would bet that 999 of your items take less RAM that all the graphics assets and sounds needed at any given time to draw a scene frame.

My posture on this: worry about RAM when the times comes and not before. If you manage to fit your entire game, or at least a whole level and then move all the heavy I/O to the loading screens that connect levels, you save yourself of having to deal with things like different hard disk speeds, something else than your game doing I/O operations at the same time, etc.

About having each item graphics loading when the player access the item description page (if this is what you are planning): It doesn't sound so terrible to me, maybe we can have a loading wheel that only the players with slower hardware will see, yet no game I have played do this leading me to believe that the items description text or graphics assets aren't a worry for the developers of those games.

RPGs with battles that moves the player away from the exploration map: maybe there is an opportunity to place disk access here. We can make the transition animation a loading screen.

Just consider the following: if data is small enough, then no matters which path you follow in respect to avoid freezing the game enough for the player to notice, probably either load from disk or already having everything in RAM will just work when you test it, but if we add to the formula that now you have to write the code to make the loading possible, that probably involves to process the format used to represent your items in disk, we have increased the complexity of the project, potentially without needed it.

You always can work in an incremental way. Design how your items will be represented in memory is something you have to do with or without the on demand loading system, so, start by designing them. Start adding items by filling an array of instances of your items, if you observe the memory go beyond what you are willing to tolerate then it's time to start your on demand loading system. The advantage is that you didn't lose any time, as the structures designed will probably remain the same, just that now instances of them won't exists on memory all time.

Same goes for everything else like monsters stats and so on.

---
Tags: rpg, data
---


# Question
Title: Rotate a UI Image exactly 360 degrees over the course of 1 second?
I have a UI Image that I want the user to click and have it rotate 360 degrees once on the z axis. I can get it to rotate through a coroutine but I'm having trouble making it stop once it is started.

```
public void getInputClick()  // OnClick method for UI object
{
    foreach (Transform child in EventSystem.current.currentSelectedGameObject.GetComponentsInChildren<Transform>())
    {
        if (child.gameObject.name == "Lock")  //Making sure this is an object that should rotate becasue it has a child named "Lock"
        {
            if (rotating == false) //enable coRoutine if not already rotating
            {
                runRotationRoutine = true;
            }
            break;
        }
    }

}

void Update()
{
    if (runRotationRoutine == true)  //Listening for coRoutine execution directive during update.
    {
        StartCoroutine(rotationRoutine());
    }
}

IEnumerator rotationRoutine()
{
    runRotationRoutine = false;  // make sure update doesnt try to run the coroutine more than once!
    rotating = true;  // bool signifying that rotation is currently happening.

    while(rotating == true)
    {
        imageObject.transform.Rotate(rotationVector);
        yield return null;

        //  This works but rotates forever because the coroutine is never terminated.

        //  How do I make this stop after the object has rotated 360 degrees????

        //  Something like (when current rotation == starting rotation --->  set rotation = false
        // But how would I determine this?
    }

}

```

It needs to be a coroutine because there are a lot of other things executing simultaneously. I feel like it should be pretty simple to just tell it to only rotate around once, what am I missing here?

# Answer
> 1 votes
You just need to keep track of how much rotation you've applied, and break out of the loop when you reach your target:

```
IEnumerator rotationRoutine()
{
    runRotationRoutine = false;
    rotating = true;
    var total_z_rot = 0.0f;

    while(rotating == true)
    {
        // prevent from over-rotating
        var z_rot = Mathf.Min(360.0f - total_z_rot, rotationVector.z);

        imageObject.transform.Rotate(new Vector3(0.0f, 0.0f, z_rot));
        total_z_rot += z_rot;

        if(total_z_rot >= 360.0f)
        {
            rotating = false;
            break;
        }
        else
        {
            yield return null;
        }
    }
}

```

---
Tags: unity, c#, rotation, transformation
---