# Question
Title: How can I scale Farseer bodies so that they work on different screen resolutions?
I created a little Windows Phone 8 game that supports multiple resolutions. If the resolution of the device is less than 720p, then the sprites and their corresponding Farseer bodies need to be scaled down. If I run my project with the 720p emulator, then everything looks fine. But if I choose an emulator with a lower resolution(for example WVGA emulator), then everything looks weird.

In this picture, I use the 720p emulator: http://s1.directupload.net/images/140520/gnpwvjsw.jpg

In this picture, I use the WVGA emulator: http://s14.directupload.net/images/140520/hxhicnph.jpg

If I use the WVGA emulator, then the Farseer collision shapes are drawn on another position than their corresponding sprites. In addition, a part of the red ball sprite is drawn in the blue rectangle sprite, but their corresponding shapes are drawn differently(the ball shape isn't in the rectangle shape).

How can I scale the Farseer bodies so that everything works correctly?

Here is my entire code:

Game1 class:

```
public class Game1 : Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    bool Draw_debugView = true;
    World world;
    Body Rectangle, Ball;
    Texture2D RectangleSprite, BallSprite;

    public Camera camera;

    public const int VirtualScreenWidth = 1280;
    public const int VirtualScreenHeight = 720;
    Vector2 vp, gameWorldSize = new Vector2(1280, 720);
    float ScaleX, ScaleY, Scale;

    DebugViewXNA physicsDebug;
    private Matrix _view;
    private Vector2 _cameraPosition;
    private Vector2 _screenCenter;

    private static float _displayUnitsToSimUnitsRatio = 100f;

    public static Vector2 ToDisplayUnits(Vector2 simUnits)
    {
        return simUnits * _displayUnitsToSimUnitsRatio;
    }

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        graphics.IsFullScreen = true;
    }

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        BallSprite = Content.Load<Texture2D>("ball");
        RectangleSprite = Content.Load<Texture2D>("tile");

        vp = new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);

        ScaleX = vp.X / gameWorldSize.X;
        ScaleY = vp.Y / gameWorldSize.Y;
        Scale = Math.Min(ScaleX, ScaleY);
        camera = new Camera(new Vector2(640,360), Scale, vp);

        _view = Matrix.Identity;
        _cameraPosition = Vector2.Zero;

        _screenCenter = new Vector2(graphics.GraphicsDevice.Viewport.Width / 2f,
                                            graphics.GraphicsDevice.Viewport.Height / 2f);

        if (world == null)
        {
            world = new World(new Vector2(0, 1));
        }
        else
        {
            world.Clear();
        }

        physicsDebug = new DebugViewXNA(world);
        physicsDebug.DefaultShapeColor = Color.White;
        physicsDebug.SleepingShapeColor = Color.LightGray;
        physicsDebug.LoadContent(GraphicsDevice, Content);

        Ball = BodyFactory.CreateCircle(world, 0.25f*ScaleX, 1.0f);
        Ball.BodyType = BodyType.Dynamic;
        Ball.Position = new Vector2(6.4f, 0.6f);
        Ball.LinearVelocity = new Vector2(0, 2.0f);

        Rectangle = BodyFactory.CreateRectangle(world, 1.50f*ScaleX, 0.50f*ScaleY, 1.0f);
        Rectangle.BodyType = BodyType.Static;
        Rectangle.Position = new Vector2(6.4f, 3.6f);
        Rectangle.Rotation = 0f;
        Rectangle.Restitution = 0.5f;
        Rectangle.CollisionCategories = Category.Cat5;
    }

    protected override void Update(GameTime gameTime)
    {
        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
        world.Step(Math.Min(elapsed, (1f / 60f)));

        ScaleX = vp.X / gameWorldSize.X;
        ScaleY = vp.Y / gameWorldSize.Y;
        Scale = Math.Min(ScaleX, ScaleY);

        //The ball should always be the center of the camera
        camera.Update(gameTime, new Vector2(Ball.Position.X*100f, Ball.Position.Y*100f), Scale, vp);

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, camera.GetMatrix());
            spriteBatch.Draw(RectangleSprite, ConvertUnits.ToDisplayUnits(Rectangle.Position),
                                           null,
                                           Color.White, Rectangle.Rotation, new Vector2(RectangleSprite.Width / 2.0f, RectangleSprite.Height / 2.0f), 1f,
                                           SpriteEffects.None, 0f);

            spriteBatch.Draw(BallSprite, ConvertUnits.ToDisplayUnits(Ball.Position),
                                     null,
                                     Color.White, Ball.Rotation, new Vector2(BallSprite.Width / 2.0f, BallSprite.Height / 2.0f), 1f,
                                     SpriteEffects.None, 0f);

        spriteBatch.End();

        if (Draw_debugView == true)
        {
            // calculate the projection and view adjustments for the debug view
            Matrix projection = Matrix.CreateOrthographicOffCenter(0f, graphics.GraphicsDevice.Viewport.Width / _displayUnitsToSimUnitsRatio,
                                                             graphics.GraphicsDevice.Viewport.Height / _displayUnitsToSimUnitsRatio, 0f, 0f,
                                                             1f);
            Matrix view = Matrix.CreateTranslation(new Vector3((_cameraPosition / _displayUnitsToSimUnitsRatio) - (_screenCenter / _displayUnitsToSimUnitsRatio), 0f)) * Matrix.CreateTranslation(new Vector3((_screenCenter / _displayUnitsToSimUnitsRatio), 0f));
            // draw the debug view
           physicsDebug.RenderDebugData(ref projection, ref view);
        }
        base.Draw(gameTime);
    }
}

```

Camera class:

```
public class Camera
{
    private Vector2 BallPosition;
    private Vector2 Viewport;
    private float Scale;

    public Camera(Vector2 ballposition, float scale, Vector2 viewport)
    {
        BallPosition = ballposition;
        Scale = scale;
        Viewport = viewport;
    }

    public void Update(GameTime gameTime, Vector2 ballposition, float scale, Vector2 viewport)
    {
        BallPosition = ballposition;
        Scale = scale;
        Viewport = viewport;
    }

    public Matrix GetMatrix()
    {
        return Matrix.CreateTranslation(new Vector3(-BallPosition.X, -BallPosition.Y, 0))
     * Matrix.CreateScale(Scale, Scale, 1)
     * Matrix.CreateTranslation(Viewport.X / 2, Viewport.Y / 2, 0);
    }
}

```

**UPDATE:** I changed my code and tried it without scaling the sprites and Farseer objects. In addition, I changed my code in the Camera class to:

```
public Matrix GetMatrix()
{
    return Matrix.CreateTranslation(new Vector3(-BallPosition.X, -BallPosition.Y, 0))
 * Matrix.CreateTranslation(Viewport.X / 2, Viewport.Y / 2, 0);
}

```

But it's still not working. I get the following result if I don't use scaling: http://s7.directupload.net/images/140523/oumh3e7c.jpg

Why is the DebugView drawn on another position than the sprites? I found out that if I change something in this code block, then the DebugView is drawn on another position, but I don't know how to change this code block so that the DebugView is drawn on the correct position(on the same position as their corresponding sprites). I know that it's not working because I use a Camera class, but how should I change this code block so that it works with the Camera class?

```
if (Draw_debugView == true)
    {
        // calculate the projection and view adjustments for the debug view
        Matrix projection = Matrix.CreateOrthographicOffCenter(0f, graphics.GraphicsDevice.Viewport.Width / _displayUnitsToSimUnitsRatio,
                                                         graphics.GraphicsDevice.Viewport.Height / _displayUnitsToSimUnitsRatio, 0f, 0f,
                                                         1f);
        Matrix view = Matrix.CreateTranslation(new Vector3((_cameraPosition / _displayUnitsToSimUnitsRatio) - (_screenCenter / _displayUnitsToSimUnitsRatio), 0f)) * Matrix.CreateTranslation(new Vector3((_screenCenter / _displayUnitsToSimUnitsRatio), 0f));
        // draw the debug view
       physicsDebug.RenderDebugData(ref projection, ref view);
    }

```

# Answer
You should abstract the dimensions of your simulations from the dimensions of your rendering. For your physics simulation just use meters and don't worry about how many pixels a meter is. You can provide `SpriteBatch.Begin` with a matrix as a parameter. That matrix applies a linear transformation to all coordinates fed to the SpriteBatch. You already have a camera class, if you apply the proper scaling there then everything should work.
> 2 votes

---
Tags: xna, c#, monogame, windows-phone-8
---


# Question
Title: Create 2D sprites with libGdx using a shape and a texture separately
I am creating a 2D game with LibGdx that will have creatures that are generated from dozens of characteristics with potentially millions of unique combinations. For each segment of each creature, I want to use two sprites so that I can mix shapes and colors and cut down on my resources. I would like one sprite to be a black and white (or grayscale) of the shape of the body part while the second sprite is just a color pattern. I think I may need to write a shader that splices the color pattern onto my shape to give me the sprite I need. I just need some guidance on how to get started.

Another way of explaining this is with the example of clothing. I want to be able to draw a shirt shape, and pants shape, a socks shape, etc. and also draw different fabric patterns. Then I would mix and match the clothing with the pattern instead of drawing every possible combination. How can I accomplish this with LibGdx?

# Answer
> 1 votes
It sounds like what you are trying to achieve is masking. You want to maintain the shape of a given sprite A (thus only specifying black/white info), while having a second sprite B to form the texture.

In this case, you can achieve what you want by using a depth buffer. The code example of achieving something like what you want is located in that same link.

---
Tags: opengl, 2d, libgdx, sprites, graphics-programming
---


# Question
Title: How can I make a spline out of three points that define a circular arc?
I was looking at the descriptions of various curve techniques here and noticed the mention of circular arcs. I want to implement something like this, but I'm not quite sure what the correct formula to use is. I can easily find formulas for Bezier or Hermite curves, but when I search for circular arc splines or circular arc interpolation I get a lot of ultra technical articles that are far beyond what I need. My hunch is that I take the angle formed between the endpoints and the control point and use that radius, but I'm still a little too wobbly conceptually to be able to guess a formula.

For those who cannot follow the link, the circle data is given by a starting point and end point which lie on the circle as well as a control point which is used to control the angle.

What formula can I use to interpolate over and approximate an arc of a circle given these three points?

# Answer
> 6 votes
Let's assume you want a circular arc from point A to point B, guided by control handle H which is the intersection of the tangents at A & B (and thus equidistant from A & B).

Circles being the bread & butter of geometry, there are a hundred ways to skin this cat - but here's one...

If we define:

```
midpoint = (A + B)/2;
perpendicular = (-(B - midpoint).y, (B - midpoint).x);

```

then this can equivalently be expressed with two points A & B and a ratio h, such that

```
H = midpoint + h * perpendicular;

```

where values of h \> 0 correspond to arcs turning to the right/clockwise from A to B, and \< 0 are arcs turning left/counterclockwise (assuming x+ points right and y+ points up - sometimes y is inverted). h = 0 is the degenerate case of a straight line - use linear interpolation if h is very close to zero, as the method is numerically unstable when the radius approaches infinity.

We can use this to compute a center point, radius, start angle, and angular delta between the points:

```
center = midpoint - perpendicular/h;

radius = Length(A - center);

startAngle = atan2(A - center);

endAngle = atan2(B - center);

angleDelta = endAngle - startAngle;
if(angleDelta * h > 0)
{
   angleDelta -= sign(h) * 2 * PI;
}

```

Then your formula for a point with interpolation weight t in \[0, 1\] along the arc is:

```
angle = startAngle + angleDelta * t;
point = center + radius * (cos(angle), sin(angle));

```

And the length of the arc is simply r * abs(angleDelta)

---
Tags: interpolation, splines
---


# Question
Title: Why are my objects rotating with my camera?
I am working with this C# library that wraps OpenGL. I am trying to understand why my objects in the scene are rotating as I yaw my camera (view matrix).

Here is an image where I have 4 separate cubes in a row with no spacing.

If I yaw my camera you can see that the cubes have also rotated. Notice the red arrows which point to the side of a cube that is now visible:

I was expecting that these cubes would not rotate. It looked to me as if something in my code is wrong for their model matrix, but I'm not sure I understand what is happening.

Every render frame I am doing this for each cube:

```
shader["model_matrix"].SetValue(ModelMatrix);

```

`ModelMatrix` is calculated as follows, once:

```
this.ModelMatrix = Matrix4.CreateTranslation(new Vector3(worldX * size, worldY * size, worldZ * size));

```

`world` variables are offsets for the position of the cube, and size is just the length. Each render frame my view matrix is being set:

```
shader["view_matrix"].SetValue(camera.ViewMatrix);

```

Here is the vertex shader:

```
uniform mat4 projection_matrix;
uniform mat4 model_matrix;
uniform mat4 view_matrix;

attribute vec3 in_position;
attribute vec3 in_normal;

varying vec3 vertex_light_position;
varying vec3 vertex_normal;

void main(void)
{
  vertex_normal = in_normal;
  vertex_light_position = normalize(vec3(1, 1, 0));
  gl_Position = projection_matrix * model_matrix * view_matrix * vec4(in_position, 1);
}

```

I have been basing this extended example off of the tutorial here. I am probably missing something basic (I am just starting OpenGL), so thanks for any help in advance!

# Answer
As DMGregory commented, your model\_matrix and view\_matrix are in wrong order in your shader code. If you look at the tutorial's shader code, you'll see your mistake.

I really liked this tutorial about matrices. It simply explains how the order of transformations and rotations should be. There is also couple great general explanations about how graphics pipeline works in computerphile's channel on youtube, including information about matrices.
> 6 votes

---
Tags: opengl, opentk
---


# Question
Title: Problems with my interpolation inplementation
When I interpolate my sprite's movement (code below), I'm curious as to whether the part where I actually apply the interpolation to the sprite's current X position (in my render call) is correct.

This is why I'm asking....

In all the examples I can find, it is pretty much like this:

```
         render(float interpolation){

            //This example shows interpolation for X axis only.

            interpolatedPosX = spriteGridX+(SpriteXVelocity*dt)*interpolation;
            spriteScreenPosX = interpolationPosX * screenWidth;

            drawSprite(spriteScreenX, spriteScreenY);
         }

```

Now, for me, this only works when the sprite is moving right(or down for sprites moving along the Y Axis, the example above uses X movement).

I have to do something like this:

```
render(float interpolation){

            //This example shows interpolation for X axis only.

     if (sprite.isGoingRight){
            interpolatedPosX = spriteGridX+(SpriteXVelocity*dt)*interpolation;
     }

     else if (sprite.isGoingLeft){
            interpolatedPosX = spriteGridX-(SpriteXVelocity*dt)*interpolation;
     }

     spriteScreenPosX = interpolationPosX * screenWidth;

     drawSprite(spriteScreenX, spriteScreenY);

 }

```

The above makes sense to me, as you add to the position to go right and subtract to go left, but I ask because I can't find an example that shows this behaviour, so I don't know if either the examples just aren't going into this detail and assume the reader will know this or I've got this wrong?

Any help would be appreciated as I'm only just starting to get to grips with interpolation!

```
public void onDrawFrame(GL10 gl) {

        //Set/Re-set loop back to 0 to start counting again
        loops=0;

        while(System.currentTimeMillis() > nextGameTick && loops < maxFrameskip){

        SceneManager.getInstance().getCurrentScene().updateLogic();
        nextGameTick+=skipTicks;
        timeCorrection += (1000d/ticksPerSecond) % 1;
        nextGameTick+=timeCorrection;
        timeCorrection %=1;
        loops++;
        tics++;

     }

        interpolation = (float)(System.currentTimeMillis() + skipTicks - nextGameTick) / (float)skipTicks;

        render(interpolation);
}

```

**Applying interpolation**

```
            render(float interpolation){

            //This example shows interpolation for X axis only.  Y position (spriteScreenY is assumed to be valid)
            interpolatedPosX = spriteGridX+(SpriteXVelocity*dt)*interpolation;
            spriteScreenPosX = interpolationPosX * screenWidth;

            drawSprite(spriteScreenX, spriteScreenY);

        }

```

# Answer
> 1 votes
First off, your branches for `sprite.isGoingRight` and `sprite.isGoingLeft` are completely identical.

```
 if (sprite.isGoingRight){
        interpolatedPosX = spriteGridX+(SpriteXVelocity*dt)*interpolation;
 }

 else if (sprite.isGoingLeft){
        interpolatedPosX = spriteGridX+(SpriteXVelocity*dt)*interpolation;
 }

```

Secondly, you don't need to branch, because `SpriteXVelocity` should be a signed value, that is if the object is moving right, the value is positive, and if left - negative.

Fixing these two issues should be enough.

# Answer
> 0 votes
First a tip: Get hold of a decent vector/matrix library that you feel comfortable using. Saves a lot of typing and makes the code much more readable

Here is an example code (not tested)

```
class Sprite{
    public:
        Vec2d position; //Where are you now?
        Vec2d target; //Where do you want to go?
        float speed=2.5f; //How fast do you want to move(pixels per second)
public:
        void update(float secondsSinceLastUpdate){
            Vec2d diff=target-position;//The vector from your current position to your target position
            Vec2d direction=diff.normalized(); //Directional vector from current to target position
            Vec2d velocity= direction*speed*secondsSinceLastUpdate;//How to move for this update
            position+=velocity;//Update position
    }

    void render(Canvas c){
        /*
        Your rendering code gores here
        c.drawSprite(sprite,position);

        TIP: update and render can be called separately.

        Usually you call update() and render() once for every frame.
        Sometimes, is your game is "hidden" you can get away with calling just the update().

        Also if the secondsSinceLastUpdate gets too big, you can call update() several times per frame, effectively keeping the game state stable even when dropping frames.

    }
}

```

EDIT: I just realized you are probably using Java instead of C++. My code is pseudo C++, and you will have to adapt it to Java (no operator overloading available there yet). that means that you will probably do something like diff=target.minus(position); instead of diff=target-position; etc.

---
Tags: movement, interpolation
---


# Question
Title: What data am I allowed to collect for statistical purpose ?
## Description

I would like to know where is **the limit between the data I am allowed to store and the data that is *private***. I don't know if there is a legal limit or if it is ethical. I know what kind of statistics the games usually display but there may be others that they hide. I would like to collect data and **combine them to make conclusions**, I don't want the player to see the raw data.

## Some examples

* **1)** Information about the character (usual data)

> * Number of type A enemy killed.
> * Max gold collected.
> * ...

* **2)** Information about the player himself

> * Number of hour played.
> * Time when he started to play.
> * Number of time playing between 11pm and 6am.
> * ...

* **3)** Information about the messages (if there is a chat in the game for example)

> * Number of message sent.
> * Most used word.
> * Most contacted person.
> * ...

I would prefer not to display a warning on the first launch of the game saying that informations are being collected or something like this.

## The actual question

My question can be separated into the following questions:

* Am I allowed to collect type 1, 2, 3 datas ?
* Is there a difference of autorisation if the datas are stored/used localy or in an online database ?

# Answer
> 1 votes
In short, the rules are pretty blurry but the big companies have consisently proved in the past that really (although this shouldn't be the case) as long as the user agrees to it in the "terms of use" or some other agreement you can technically record anything you like.

The point at which things get really complicated is around financial data like bank or card details where there are standards around how the data must be stored in order to prevent the data being stolen and used elsewhere.

Since this is purely game related data I would be inclined to say that when the user signs up technically you already got the "worst" bit of data in this sense of the word in that you took a bunch of personal information (name, address maybe, email address, possibly even age / dob).

The key is pre agreed terms of use, without which you can hit problems further down the line.

Did you know:

Microsoft famously put a clause in the windows EULA stating they can delete software from your pc they deem "illegal".

Facebook have been slated for sharing personal information despite their terms of service stating that users technically cannot prevent this by using their service.

There are plenty of examples of companies succumbing to government or organisations like the NSA and opening up access to their databases without prior approval from the owner of that data (the signed up user) on the grounds of "crime prevention".

---
Tags: statistics
---


# Question
Title: Converting a GameObject method call from UnityScript to C#
Here is the UnityScript implementation of the method i use to generate a randomly tiled background, the problem i'm having relates to how to translate the call to the newTile method in c#, so far i've had no luck fiddling... can anyone point me in the correct direction?

Thanks

```
#pragma strict
import System.Collections.Generic;

var mapSizeX : int;
var mapSizeY : int;
var xOffset : float;
var yOffset : float;

var tilePrefab : GameObject;
var tilePrefab2 : GameObject;

var tiles : List.<Transform> = new List.<Transform>();

function Start () {
    var i : int = 0;
    var xIndex : int = 0;
    var yIndex : int = 0;
    xOffset = 2.69;
    yOffset = -1.97;

    while(yIndex < mapSizeY){
       xIndex = 0;
       while(xIndex < mapSizeX){

                var z = Random.Range(0, 5);

                if (z > 2)
                {

                 var newTile : GameObject = Instantiate (tilePrefab, Vector3(xIndex*0.64 - (xOffset * (mapSizeX/10)), yIndex*-0.64 - (yOffset *  (mapSizeY/10)), 0), Quaternion.identity);
                 tiles.Add(newTile.transform);
                 newTile.transform.parent = transform;
                 newTile.transform.name = "tile_"+i;
                 i++;
                 xIndex++;

                 }

                 if (z < 2)
                {

                 var newTile2 : GameObject = Instantiate (tilePrefab2, Vector3(xIndex*0.64 - (xOffset * (mapSizeX/10)), yIndex*-0.64 - (yOffset *  (mapSizeY/10)), 0), Quaternion.identity);
                 tiles.Add(newTile2.transform);
                 newTile2.transform.parent = transform;
                 newTile2.transform.name = "Ztile_"+i;
                 i++;
                 xIndex++;

                }

       }

       yIndex++;
    }
}

```

C# Version \[Fixed\]

```
using UnityEngine;
using System.Collections;

public class LevelGen : MonoBehaviour {

    public int mapSizeX;
    public int mapSizeY;
    public float xOffset;
    public float yOffset;

    public GameObject tilePrefab;
    public GameObject tilePrefab2;

    int i;

    public System.Collections.Generic.List<Transform> tiles = new System.Collections.Generic.List<Transform>();

    // Use this for initialization
    void Start () {

        int i = 0;
        int xIndex = 0;
        int yIndex = 0;
        xOffset = 1.58f;
        yOffset = -1.156f;

        while (yIndex < mapSizeY)
        {
            xIndex = 0;
            while(xIndex < mapSizeX) {

                int z = Random.Range(0, 5);

                if (z > 5)
                {
                    GameObject newTile = (GameObject)Instantiate(tilePrefab, new Vector3(xIndex*0.64f - (xOffset * (mapSizeX/10.0f)), yIndex*-0.64f - (yOffset *  (mapSizeY/10.0f)), 0), Quaternion.identity);
                    tiles.Add(newTile.transform);
                    newTile.transform.parent = transform;
                    newTile.transform.name = "tile_"+i;
                    i++;
                    xIndex++;

                }

                if (z < 5)
                {
                    GameObject newTile2 = (GameObject)Instantiate(tilePrefab, new Vector3(xIndex*0.64f - (xOffset * (mapSizeX/10.0f)), yIndex*-0.64f - (yOffset *  (mapSizeY/10.0f)), 0), Quaternion.identity);
                    tiles.Add(newTile2.transform);
                    newTile2.transform.parent = transform;
                    newTile2.transform.name = "tile2_"+i;
                    i++;
                    xIndex++;
                }

            }
            yIndex++;
        }

    }

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

    }
}

```

# Answer
> 1 votes
So we can mark it as answered I've reformatted the details you have put up. Can you please revert your changes in your question so future viewers can see what changes were made if they have the same issue.

Also I noticed you have a lot of logic redundancies (like your if (z\>5) and if (z\<5)) as they can be condensed into an `if(){}else{}` statement with a smaller random range, considering `z` is used for nothing but a Rand comparison.

C# Version:

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

public class LevelGen : MonoBehaviour {

    public int mapSizeX;
    public int mapSizeY;

    public GameObject tilePrefab;
    public GameObject tilePrefab2;

    private float xOffset;
    private float yOffset;
    private int i;

    public List<Transform> tiles =
        new List<Transform>();

    // Use this for initialization
    void Start ()
    {
        int i = 0;
        int xIndex = 0;
        int yIndex = 0;
        xOffset = 1.58f;
        yOffset = -1.156f;

        while (yIndex < mapSizeY)
        {
            xIndex = 0;
            while(xIndex < mapSizeX)
            {
                Vector3 tilePosition =
                    new Vector3(xIndex * 0.64f - (xOffset * (mapSizeX / 10.0f)),
                                yIndex * -0.64f - (yOffset *  (mapSizeY / 10.0f)),
                                0f);

                GameObject newTile =
                    (GameObject)Instantiate(tilePrefab,
                                            tilePosition,
                                            Quaternion.identity);

                int z = Random.Range(0, 3);
                if (z > 1)
                {
                    tiles.Add(newTile.transform);
                    newTile.transform.parent = transform;
                    newTile.transform.name = "tile_"+i;
                    i++;
                    xIndex++;
                }
                else
                {
                    tiles.Add(newTile.transform);
                    newTile.transform.parent = transform;
                    newTile.transform.name = "tile2_"+i;
                    i++;
                    xIndex++;
                }
            }
            yIndex++;
        }
    }

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

```

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


# Question
Title: What is the simplest algorithm or pattern to continues ground/Floor
Im beginner in 3d gaming , i have basic question not Language specific.
Say i have ground model for example terrain i modeled what is the common way to load the terrain and use it again Or load another terrain when
the main model for example AirCraft im controlling in the game approaching its end , and i want the player to see the terrain continue like in never ending world .

# Answer
> 1 votes
I think the simplest way is to divide your terrain into grid and manage which grid tiles to load/unload.

Let's assume you want to have 3x3 grid all the time, with one center tile under your player, and one additional tile in each direction. Now, during every frame you check if your player has moved to another tile and if so, you load new tiles in the direction of movement and unload the tiles that are too far away. After this load/unload phase you'll still have a 3x3 grid centered over your player.

I can't make you a fine picture of it now but here's some sketch: link

This way you can manage quite big terrains but there're some problems you should know:

### Tiles connection

You need to make sure that the shape of some tile at its edge is the same as the shape of its neighbor (the second tile that shares this edge) or you'll get holes in your terrain. It's quite easy if you use procedural data, like Perlin noise but it's very hard to model such meshes in 3D modelling application.

### Grid size and scale

You can split your grid into 3x3 or even 10x10 tiles. Every tile can be few meters in size or i.e. 1km - all this depends on your specific needs. If you manage many small tiles your load/unload times will be smaller but you'll do it more often. Additionally, when you make game like a flight simulator you'll need different setup than for FPS.

### Deferred loading

It's not a 'problem' but I've seen some interesting optimisation that I could share. It was in the Terrain Manager for the Ogre engine. It was also grid-based but much more complicated, with Quad-Trees, LOD, tile stitching, etc.

The trick was done during load/unload phase, where instead of checking `Which tiles should I load?` they checked `What is the first tile should I load?` then the Manager loaded only this one tile and returned control to the engine. In the next frame Manager did the same check and loaded 1 another tile. In this simple way you can split your loading into multiple frames, which lowers your FPS variations.

---
Tags: algorithm, terrain
---


# Question
Title: How do I implement space partitioning in entity component system?
My systems work on components without needing to now anything about entities. I want to implement simple grid partitioning, so each entity will be given a cell based on its current position. But how will systems know which components to update and how? For example: CollisionSystem must check collision between each components within a cell, but CollisionComponents must be somehow attached to the grid for system to know what collision to test, which doesn't seem like a good solution. What should I do?

# Answer
> 1 votes
**Artificial intelligence** components (for example) must know the state of the world in order to make decisions: There is nothing inherently wrong with letting a component have access to outside world state.

However, **collision detection** is *typically* (not always) handled by a function that sits outside of the elements to be collided. This is a matter of scope / context. In order to reduce coupling, which seems to be your intent, it is better to have one of the supersystems which already have access to all entities (bodies), apply the collisions. This prevents entities from having to know about one another, and it also allows fine control over the ordering of collision detection and resolution, which is crucial.

So, you have your game loop. Somewhere in there you have a phase where you're processing collision detection and resolution. The wise choice would be to factor that out either into a separate function or even a whole separate class, depending on your language and architectural preference.

Given that you desire spatial partitioning over your world space, I would suggest implementing a discrete class `CollisionManager`. Therein, create your partitioning structure. You could add / remove entities to `CollisionManager` at creation / expiry of those entities, and most importantly, call `CollisionManager.update()` on each global update, ensuring that everything -- both moving between partitions (based on entity translations performed just prior via other subsystems) and testing for and resolving collisions within partition locales -- is resolved compactly via a single method call.

As for your entity components associated with physics, the only purpose they serve here is to supply their respective positions and bounds information to `CollisionManager`.

---
Tags: architecture, entity-system, collision-resolution
---


# Question
Title: How to increase the game "level" after certain amount of objects spawned?
The game is supposed to increase the level by 1 every 10 spawns of an object, using totalShots % 10 == 0. So, when totalShots is equal to 10, 20, 30, etc. the level should increase by 1, however, the level keeps on increasing in the time between the 10th and 11th spawn (example: http://gfycat.com/ArtisticAdorableGreatwhiteshark).

This is the code:

```
var totalShots : int = 0;
var level : int = 0;

function Start () {

}

function Update () {
    transform.Translate(Vector3(0, direction * speed * Time.deltaTime, 0));
    if (Time.time > lastSpawn + nextSpawn){
        Instantiate(shot, new Vector3(transform.position.x - 1, transform.position.y, transform.position.z), Quaternion.identity);
        totalShots++;

    lastSpawn = Time.time;
    nextSpawn = Random.Range(2, 3);
    }

}

function ShotCounter() {
    if(totalShots % 10 == 0){
        level++;
    }
    return(level);
}

```

Should this code be working or is there something that I am doing wrong? How can I make it so that the level only increases by 1?

# Answer
> 2 votes
You have a case where several frames meet the condition of (totalShots % 10 == 0). The best way to fix this would be to check if we need to increment the level only after we increment totalShots. This will also increase game performance by decreasing the frequency of checking for this condition to only after the respective variable is updated, instead of checking for this condition on every frame.

```
function Update () {
transform.Translate(Vector3(0, direction * speed * Time.deltaTime, 0));
if (Time.time > lastSpawn + nextSpawn){
    Instantiate(shot, new Vector3(transform.position.x - 1, transform.position.y, transform.position.z), Quaternion.identity);
    totalShots++;
    if(totalShots % 10 == 0){
        level++;
    }

    lastSpawn = Time.time;
    nextSpawn = Random.Range(2, 3);
}

```

# Answer
> 5 votes
Well the `totalShots` value stays at 10 until you increase it, so `totalShots % 10 == 0` will continue to be true until you increment `totalShots` the next time, so if you keep calling `ShotCounter()` it will increment the `level`.

You need to only either call it only once, or add some other check into it. I suppose the easiest fix would be to call `ShotCounter()` right after incrementing `totalShots`, so it's only executed when that value changes.

# Answer
> 0 votes
Do u have the function ShotCounter() inside the main loop? Between the 10th and 11th spawn this function is being called maybe 100 times doing 100 level++, try to avoid that.

If u want to call the method inside the main loop u can change the function by that:

function ShotCounter() { level=totalshots/10;

}

11/10 is 1,1 then is assigned in an integer(level) being the new assignanent 1 without the .1

# Answer
> 0 votes
I am not sure where are you calling your `ShotCounter()` method, so I can give you a generalized solution on this.

You'll definitely need a second condition before you choose to increment the level count. One way would be to have a boolean field which'll be true as soon as you increase the `totalShots` variable. Check it as another condition in your `if` statement and if the level increases then make it false, so that level doesn't get increased before next increment of `totalshots`.

**Code snippet 1:**

```
var totalShots : int = 0;
var level : int = 0;
var isIncrementAllowed : bool = false;

function Start () {

}

function Update () {
    transform.Translate(Vector3(0, direction * speed * Time.deltaTime, 0));
    if (Time.time > lastSpawn + nextSpawn){
        Instantiate(shot, new Vector3(transform.position.x - 1, transform.position.y, transform.position.z), Quaternion.identity);
        totalShots++;
    isIncrementAllowed = true;

    lastSpawn = Time.time;
    nextSpawn = Random.Range(2, 3);
    }

}

function ShotCounter() {
    if(totalShots % 10 == 0 && isIncrementAllowed){
        level++;
        isIncrementAllowed = false;
    }
    return(level);
}

```

Another way would be to save LastTotalShots in a variable and check if it's the same count or not. It'll remove any possibility of incrementing a level at similar totalShots count twice.

**Code snippet 2:**

```
var totalShots : int = 0;
var level : int = 0;
var lastTotalShots : int = 0;

function Start () {

}

function Update () {
    transform.Translate(Vector3(0, direction * speed * Time.deltaTime, 0));
    if (Time.time > lastSpawn + nextSpawn){
        Instantiate(shot, new Vector3(transform.position.x - 1, transform.position.y, transform.position.z), Quaternion.identity);
        totalShots++;

    lastSpawn = Time.time;
    nextSpawn = Random.Range(2, 3);
    }

}

function ShotCounter() {
    if(totalShots % 10 == 0 && lastTotalShots != totalShots){
        level++;
        lastTotalShots = totalShots;
    }
    return(level);
}

```

---
Tags: unity, javascript, unityscript
---


# Question
Title: Smooth moving on tile-based map, how to fix simple collisions?
I've already had some experiences about the work of 2 dimensional square-based playfields and moving a player on them. Though, when a square has multiple pixel sizes, and player moves e.g. 1 pixel per frame, I have some problems. Currently, my program counts the coordinates of tile Player stands on like this:

Tile X coordinate = floor of Player X coordinate divided by the X size of a tile a.k.a `TileX = floor(PlayerX/TileXsize)`

and same for Y. However, when I increase the moving speed to bigger px/frame speed, sometimes the player sinks into the tile that should stop it. How can I prevent this problem?

EDIT: codes. Language is Lua, framework is LOVE2D, gamefield is stored in tables. Player has an X, an Y, and Tilex&TileY, count this way on every frames:

```
Player.TileX = math.floor((Player.X)/TileSize)
Player.TileY = math.floor((Player.Y)/TileSize)

```

Moving belongs to key actions, they are simply like `Player.X = Player.X + 1`

There's a Gravity function as well, called on every frames:

```
function Gravity()
    if not Solidchecker(Field[Player.TileX][Player.TileY+1]) then
        Player.Y = Player.Y +GForce
    end
end

```

In case of any`Gforce` (which is a constant) where value is different from the size of the tile (24) the player sinks into the ground. Obviously in that case, everythings the same as if the system would be counted with only tiles, without separated Player.TileX calculations. Otherwise, it can't handle the occuring alignment.

Possibly I forgot showing some code parts, but I can't see now that any other functions would influence these variables.

# Answer
If you want a quick solution to your algorithm, there's something that you may like :

```
function Gravity()
    for var i=1,GForce do
        if not Solidchecker(Field[Player.TileX][Player.TileY+1]) then
            Player.Y = Player.Y + 1
        end
    end
end

```

I'm only guessing that GForce is not a float number, and that it's close to 1.

This way it will move one tile at a time, stopping either at the closest Solidchecker being true, either at GForce.
> 2 votes

# Answer
First, stucking and penetrating are common problems in physics simulation: on high enough speeds objects may teleport through obstacles or stuck deepd inside in solid volumes.

Typical solution will be either to move object back to last known non-stuck position (you need to save these coordinates somewhere) or gradually move object back to that position until you hit unobstructed place.

But these methods wont solve issue with teleportation throuh obstacles, when objects are moving fast or when obstacles are small (like 1 px walls). So if you want really good physics, use physics engine, it will save tons of headache.

Second, if players collision bounds are bigger than single pixel, or he is one pixel size but physics precision is better than 1 pixel, then player can actually occupy multiple tiles. Imagine him standing right between adjacent 2 tiles, or in center of 2x2 box. This may or may not be issue depending on game.
> 2 votes

---
Tags: 2d, collision-detection, tiles, lua, love2d
---


title: Send request for Turned Based Battle

text:
# Question
Title: Send request for Turned Based Battle
I want to create a turn based battle system for Pokemon online rpg!

I will some how implement the coding of the battle..but I want to know how can a user send request for a battle to other user?

If a user wants to have a live battle with some other user, he will send a battle request! If the opponent wants to battle he will accept it otherwise it will be rejected and no battle will take place...!

How can I implement the above??

# Answer
You will need some client Javascript and run AJAX regularly so you can run server-side PHP and check if there are any battle requests, or during combat turns to check for any player actions.
> 1 votes

---
Tags: php, turn-based, ajax
---


# Question
Title: How to store and use different AI behaviours
I'm coding a space shooter on three.js (WebGL) and since the game I'm doing is rather simple, plus I want to keep controll of the structure, I'm not using a game engine.

I'm using oop classes and inheritance to optimize code reusability and maintenability.

The classes so far look like the following :

**MovingObject**, the base class possessing the attributes : position, speed, weapon, mesh, etc.

**Asteroid**, inheriting MovingObject

**PlayerShip**, inheriting MovingObject

**Weapons**, Base class of other weapons, possessiong the class shoot, that every other inheriting class redefines in order to shoot the projectile it wants at the position and frquency it wants

**MovingSystem**, Base class of other moving classes, possessing the function update(inputs,time) that move the MovingObject according to the class behaviour

What I'm searchign is a common architecture / data-model of how an AI controlling an enemy space ship should look like.

So far I've only found algorithms of A\* search, a following / escaping path search, etc.

However I don't need the logic code, I want **the structure of HOW and WHERE to execute the AI**. (If possible in an oop model, so there can be inheritances with slight variations)

I'll post an example of code here, so you see how the code actually use the different classes and inhertance :

```
//MovingObject class
MovingObject.prototype.update = function(time, inputs)
{
    this.lastPos = this.mesh.position.clone();
    //console.log("this: ",this);
    //console.log("inputs: ", inputs);
    this.movingSys.move(this, time, inputs);

    this.particularUpdateFunctions(time);
};
//PlayerShip class
function PlayerShip(MAX_SPEED, speed, COEFF_ACCEL, mesh)
{
    this.particularUpdateFunctions = function(time){
        this.weapons[this.currentWeap].update(this,time, this.shooting);
    };
}

```

# Answer
> 1 votes
**Disclaimer**: "typically" applies to all of the following since no two game architectures are the same.

AI is executed near or at the start of the game loop, usually just after or before user input. Why? Because both player(s) and AI(s) are entities, and they each have their own way of providing input. For the player, your code extracts actions from human interface devices, and for the AIs your code does the thinking to decide what moves to make. Both should result in a command or command queue, which will then be enacted in the next phase of the current game loop iteration, or in future iterations.

"**HOW** to execute" your AI is not something we will be able to help you with, I'm afraid, since there is no single way of doing this... it is a very broad question and depends on what you're trying to achieve. Architecturally though, suffice to say that if your game is quite simple, you may want to use an FSM to produce your commands to be stored in and executed from the command queue.

Commands would generally be things like, "move forward", "fire", "jump" and so on. These could be enacted without knowing or caring whether the entity is player- or AI-controlled. These would typically have a duration, which could be a single frame / update, or more often, several updates before completion. On completion, we'd check the command queue for the next command, and enact it, etc.

---
Tags: architecture, javascript, algorithm, ai, oop
---


# Question
Title: Displaying streaming video on dynamic texture
We are working in Unity 3D on pro licence and we are faced with the task to display streaming video as a dynamic texture in out Unity3D web project. We have a standard IP-camera , which is capable of delivering a stream h.264 format via RTSP, and mjpeg via HTTP.

How can we display this stream on a texture in our scene?

# Answer
Unity Pro has movie textures built in for streaming different types of movie files to an in-world texture.

If that doesn't work for you, you can build a custom solution around RTT, also a Pro feature.

AFAIK, there are already video streaming solutions available in the Unity Asset Store. A quick google search will do wonders for you.
> 2 votes

---
Tags: unity, textures, camera, video, streaming
---


# Question
Title: How can I locate the frames of a spritesheet PNG based on this PLIST data?
Someone asked me to reskin a certain game. Now he only sent me the whole sprite PNG and PLIST files of the sprites. He instructed me to rename each sprite with the same name corresponding to each original sprite.

The problem is, he gave me the whole sprite sheet instead of each individual sprite and the PLIST. Now yes, I can read the PNG filenames from the PLIST, but I cannot rename the reskin sprites I did because I'm not sure which sprite is boy\_gun\_3\_3.png; there are multiple guns, I don't know which is which.

Is there a way to extract individual accurately named individual PNG files from the single sprite sheet using the PLIST?

# Answer
A `.png` is a generic image format, and a `.plist` is a generic key-value "property list" format. Neither are *inherently* concerned with sprites or sprite sheets.

That means the answer to this question depends highly on what's in files -- primarily the `.plist` file.

Normally any sort of spritesheet metadata (which is what your `.plist` sounds like) has both sprite frame names and the positions of each frame. Or something similar, like sequence names and sequence boundaries, where each frame in a sequence is a fixed size.

If you have this size and position information available in the sprite, you can interpret it to know how to extract the individual sprites associated with the individual names. If you do not have this information in the `.plist`, you probably can't correlate the names in the property list file to the frames in the image.

(It's possible that the organization of the file is such that each sprite is a fixed size and they match 1:1 in a certain order (for example, you look at individual frames from left-to-right, top-to-bottom, and that traversal of the `.png` corresponds to a document-order traversal of the `.plist`), in which case you also have sufficient information to do the correlation you want, but that's going to depend on the author of the data.)
> 1 votes

---
Tags: sprites, cocos2d, spritesheet, png
---


# Question
Title: What does this FVF value in the FVFData block of an .X file equate to?
I'm trying to read and ultimately write a mesh from/to file. This mesh has 2 sets of texture coordinates. The second set I know are held within the FVFData{} block of the .x file. The second set of coordinates is the only data within this block...the block looks like this:

```
FVFData {
258;
60;
1050755713,
1060090006,
...
}

```

This is 30 sets of 2 floating point values...

258 is equal to 0x102... D3DFVF\_TEX1( 1, 2-component vector ) is equal to 0x100... ...where does the extra 0x002 come from? is that just D3DFVF\_XYZ..? ...why are they coupled for this data block when there is no position data in the block?

# Answer
From the D3D9 headers (specifically, `d3d9types.h`), you can see that `D3DFVF_TEX1` is indeed 0x100 and `D3DFVF_XYZ` is 0x2; that means the FVF for that line is equivalent to `D3DFVF_XYZ | D3DFVF_TEX1`.

That's not invalid, though it sounds like it doesn't make sense in your context. It's not really possible to determine how the value got there with the limited information you've provided. My first guess would be a faulty assumption in the exporter being used that *assumes* all flexible vertex specifications would include positional data.
> 0 votes

---
Tags: c++, directx9, file-format
---


title: Transforming Normals in Bump Maps

text:
# Question
Title: Transforming Normals in Bump Maps
## Question

I have a noise texture (perlin noise, to be precise) with its value in the alpha channel and the normal components in `rgb`. I now wish to, on the fly, apply some function to the alpha part of the texture. Is there an easy way to calculate the new normal?

My thoughts are that if we know the form of `f`, then

```
∂f/∂x = df/da * ∂a/∂x

```

Now, we want to know `∂f/∂x` as from this we can calculate the `x` component of the normal, we know `df/da` as we know the form of `f(a)` and `∂a/∂x` is encoded in the normal that we are given in the first place.

## Context:

I am creating a procedural rock shader and want some "cracks". To do this I need to take my lumpy perlin noise and apply some function to it. At the moment the function is:

```
f(x) = 1 - 5.5 * abs(noise);

```

This makes it more sharp (`noise` runs from `-1` to `1`).

Here is the basic noise:

And here it is after my transformation:

Here are the normals for the first noise:

What are the normals for the second? You may notice that the given normals are very "steep" This is because the bump map they are computed from goes to +-1 several times per unit area. I thus also need to know the answer to this question so that I can scale down the noise and keep the normals correct.

# Answer
So, you have a noise function from RxR to R, called f(x, y). You are applying on that function a new transformation:

```
t(x, y) = 1 - 5.5 * f(x, y)

```

You seem to know the normals of `z = f(x, y)`, which are proportional to the gradient of the equivalent implicit function `F(x, y, z) = f(x, y) - z = 0`. The normal vector is then:

```
   (∂F(x, y, z)/∂x , ∂F(x, y, z)/∂y , ∂F(x, y, z)/∂z)
 = (∂f(x, y)/∂x    , ∂f(x, y)/∂y    , 1)
 = 1/b * (r, g, b)    // proportional to your rgb values that represent the normal
 = (r/b, g/b, 1)

```

Where `r^2 + g^2 + b^2 = 1`.

So, now you want to calculate the new normals of `t(x, y)`, which are again proportional to the gradient of the implicit function: `T(x, y, z) = t(x, y) - z = 0`. So you need:

```
   ( ∂T(x, y, z)/∂x          , ∂T(x, y, z)/∂y          , ∂T(x, y, z)/∂z )
 = ( ∂t(x, y)/∂x             , ∂t(x, y)/∂y             , 1  )
 = ( -5.5 * ∂abs(f(x, y))/∂x , -5.5 * ∂abs(f(x, y))/∂y , 1  )
 = ( -5.5 * r/b              , -5.5 * g/b              , 1  ) // TODO sign switch of abs

```

This is a problem, since the derivate of `abs(x)` is undefined for x = 0. Maybe, you can use `x^2` instead. If you really want to, you could also use 0 as derivate of `abs(x)` for x = 0.

If you use `abs(x)`, you will have to program an if-statement that checks wether f(x, y) is less then, equal or greater than zero. Accordingly change the sign, or make zero.

So, conclusion, your gradient scales by factor 5.5 for the x and y components, which makes sense, because your function is a lot steeper. And it is also possible to get a sign switch. However, we are not done yet! To get the normals, you need to normalize them, which means you have to divide them by their lengths. The length of the not normalized normal vector is:

```
 N = sqrt((-5.5 * r/b)^2 + (-5.5 * g/b)^2 + 1)

```

Now, normalizing the vector gives us:

```
  (-5.5 * r/b, -5.5 * g/b, 1) / sqrt((-5.5 * r/b)^2 + (-5.5 * g/b)^2 + 1)
= (-5.5 * r/b, -5.5 * g/b, 1) * b / sqrt((-5.5 * r)^2 + (-5.5 * g)^2 + b^2)
= (-5.5 * r, -5.5 * g, b) / sqrt((-5.5 * r)^2 + (-5.5 * g)^2 + b^2)

```

In code this means you would have:

```
for-each (pixel p(v, n_x, n_y, n_z) of my texture)
{
   pixel newPixel;
   newPixel.v = 1 - 5.5 * p.v;
   float invNorm = 1 / sqrt( (-5.5 * p.n_x)^2 + (-5.5 * p.n_y)^2 + p.n_b^2 );
   newPixel.n_x = -5.5 * sgn(p.n_x) * p.n_x * invNorm;
   newPixel.n_y = -5.5 * sgn(p.n_y) * p.n_y * invNorm;
   newPixel.n_z = p.n_z * invNorm;
}

```

Where `sgn(float)` is:

```
float sgn(float f)
{
   if (f < 0) return -1;
   if (f > 0) return 1;
   return 0;
}

```

However, it seems like you are clamping the values. If your value is clamped, use normal (0, 0, 1).
> 1 votes

---
Tags: normals, bump-map
---


# Question
Title: SpriteBatch, trying to reduce draw calls
This my main draw call:

```
       Matrix Camera_transformation = player_camera_.GetTransformation();

        // Background - AlphaBlend
        spritebatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, Camera_transformation);
        background_.Draw(spritebatch);
        spritebatch.End();

        // Particles (of a player power, I want them behind him!) - Additive
        spritebatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, null, null, null, null, Camera_transformation);
        player_.DrawParticles(spritebatch);
        spritebatch.End();

        // Player - Alpha Blend
        spritebatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, Camera_transformation);
        player_.Draw(spritebatch);
        spritebatch.End();

        // Hub/Ui - Not to be influenced by the camera, but always on top
        spriteBatch.Begin();
        UI.Draw(spritebatch)
        spriteBatch.End();

```

Is there a way to reduce the number of calls here? If my particle system didn't need an additive drawing, I would have merged the first three calls, but I can't. Is there something I am missing about spritebatch ordering?

# Answer
Changing the SpriteSortMode to Immediate is faster in the cases when the overhead of creating new batches is more signifigant than the time saved by batching. If this is the case in your situation the below will be faster. While the mode is immididate you can alter the GrahpicsDevice's state and it will impact subsiquent draw calls.

```
    Matrix Camera_transformation = player_camera_.GetTransformation();

    spritebatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null,
        null, null, null, Camera_transformation);

    // Background - AlphaBlend
    background_.Draw(spritebatch);

    // Particles (of a player power, I want them behind him!) - Additive
    GraphicsDevice.BlendState = BlendState.Additive;
    player_.DrawParticles(spritebatch);

    // Player - Alpha Blend
    GraphicsDevice.BlendState = BlendState.AlphaBlend;
    player_.Draw(spritebatch);
    spritebatch.End();

    // Hub/Ui - Not to be influenced by the camera, but always on top
    spriteBatch.Begin()
    UI.Draw(spritebatch)
    spriteBatch.End();

```
> 0 votes

---
Tags: xna, c#, xna-4.0, spritebatch
---


# Question
Title: Libgdx: movement of scrolling background is not smooth even at 60fps
I'm developing a game and I want to make a sliding background. The background is not scrolling smoothly. I logged the fps, but it was ok. This is my code, I don't know what I'm doing wrong, any ideas?

```
public class MyGdxGame implements ApplicationListener {
    private OrthographicCamera camera;
    private SpriteBatch batch;
    Texture back;
    float offset =  0f;

    FPSLogger logger = new FPSLogger();
    @Override
    public void create() {
        camera = new OrthographicCamera(320, 480);
        camera.position.set(320 / 2, 480 / 2, 0);
        camera.update();
        batch = new SpriteBatch();
        batch.setProjectionMatrix(camera.combined);
        back= new Texture(Gdx.files.internal("back.png"));
    }

    @Override
    public void dispose() {
        batch.dispose();
    }

    @Override
    public void render() {
        logger.log();
        offset +=  (400f * Gdx.graphics.getDeltaTime());
        offset = offset % 480f;
        batch.begin();
        batch.draw(back, 0, offset);
        batch.draw(back, 0, offset - 480);
        batch.end();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

```

I uploaded the code to bring more information, I looked for on internet and a lot of people have the same problem, but I didn't find solution. I have almost finished the game, change the library will be a pity, any can help me? Thanks! This is the code: https://www.dropbox.com/sh/t26gt33wcex5izn/AAD8-yBSOztZfHe4wzDPRjjQa

# Answer
> -1 votes
Well, I asked the same question in the libgdx forum so here I share the response I got in case someone has the same problem.

> You didnt find a solotion, because there isnt one. Fps loggers spits out avarage framerate. Since you dont have total control over hardware, stuff is going on in the background. And this stuff will make your stuff slow down randomly. Or cause gc or something. Focus on makaing interesting game and most people wont notice. Unless you cause gc then they will.

It's a shame to have to migrate everything, but this is not a good framework at least for me.

# Answer
> 3 votes
Without any further information (and you don't provide enough for us to give a positive answer for sure), the most likely solution for your problem is that you're introducing some granularity you don't realise. For example the line:

`offset += 400 * Gdx.graphics.getDeltaTime();`

Gdx.graphics.getDeltaTime() will return a float, and it will likely be a very small float. At 60fps, the result of that equation will be somewhere near 6.6666666... But if offset is an integer, then it will either increase by 7 units each update. That .6666666 will get thrown away, and your background will move 0.3333333 further than it should have done. Over time that error will accumulate. If the frame rate was perfectly constant, you might not notice, because it would always be 6, or always 7, and would appear perfectly constant as well, even though it's actually moving slower or faster than it actually should be.

If your framerate varies up to ~62 fps, then offset will suddenly start advancing by 6 every update instead of 7, a decrease in speed of almost ~15% even though the frame-rate has only increased by ~3%. This will manifest as a kind of jitter, moving slower or faster as the frame-rate varies.

The obvious solution there is to make `offset` a float, so that any movement less than 1px is preserved, and when accumulated will give the correct rate of motion. That may not be the only extra granularity in your system though, but you've not given us enough information to diagnose any better than that.

---
Tags: physics, libgdx, movement
---


title: Networking for Real Time Strategy games

text:
# Question
Title: Networking for Real Time Strategy games
I'm developing a real time strategy game for a computer science course I'm taking. One of the harder aspects of it seems to be client-server networking and synchronization. I've read up on this topic (including *1500 archers*), but I've decided to take a client-server approach as opposed to other models (over LAN, for instance).

This real time strategy game comes with some problems. Thankfully, every action the player takes is deterministic. However, there are events that happen on scheduled intervals. For instance, the game is made up of tiles, and when a player takes a tile, the 'energy level', a value on that tile, should grow by one every second after it's taken. This is a very quick explanation that should justify my use case.

Right now I'm doing thin clients, which just send packets to the server and wait for a response. However, there are several problems.

When games between players develop into endgame, there are often over 50 events per second (due to the scheduled events, explained earlier, piling up), and synchronization errors start to show up then. My biggest problem is that even a small deviation in state between clients could mean different decisions the clients take, which snowball into entirely separate games. Another problem (which isn't as important right now) is that there is latency and one has to wait a few milliseconds, even seconds after they make their move to see the result.

I'm wondering what strategies and algorithms I could use to make this easier, faster, and more enjoyable for the end-user. This is especially interesting given the high amount of events per second, along with several players per game.

TL;DR making an RTS with \>50 events per second, how do I synchronize clients?

# Answer
Your goal of synchronizing 50 events per second in real-time sounds to me like it is not realistic. This is why the lock-step approach talked about in the 1500 archers article is, well, talked about!

In one sentence: The only way to synchronize too many items in too short time over a too slow network is to NOT synchronize too many items in too short time over a too slow network, but instead progress state deterministically on all clients and only synchronize the bare necessities (user input).
> 12 votes

# Answer
> every action the player takes is deterministic, however, there are events that happen on scheduled intervals

I think there's your problem; your game should only have one timeline (for gameplay-affecting things). You say that certain things grow at a rate of X *per second*; find out how many game steps are in a second and convert that to a rate of X *per Y game steps*. Then even though the game may slow down, everything stays deterministic.

Having the game run independently to real time has other advantages:

* you can benchmark by running it as fast as possible
* you can debug by slowing the game way down to see fleeting events, and as mentioned
* the game stays deterministic which is very very important for multiplayer.

You also mentioned that you run into problems when there are \>50 events, or there are delays of up to seconds. This is much smaller in scale than the scenario described in *1500 archers*, so see if you can profile your game and find out where the slowdown is.
> 6 votes

# Answer
First, to solve the problem with scheduled events, **don't broadcast the events when they happen**, but when they're initially scheduled. That is, instead of sending an "increment the energy of tile (*x*,*y*)" message every second, just send a single message saying "increment the energy of tile (*x*,*y*) once per second until it is full, or until interrupted". Each client is then responsible for scheduling the updates locally.

In fact, you can take this principle further, and **only transmit player actions**: everything else can be computed locally by each client (and the server, as necessary).

(Of course, you probably should also occasionally transmit checksums of the game state, to detect any accidental desynchronization, and have some mechanism for re-synchronizing clients if that happens, e.g. by resending all the game data from the server's authoritative copy to the clients. But this should hopefully be a rare event, only encountered in testing or during rare malfunctions.)

---

Second, to keep the clients synchronized, **make sure that your game is deterministic.** Other answers have already provided good advice for this, but let me include a brief summary of what to do:

* Make your game internally turn-based, with each turn or "tick" taking, say, 1/50 seconds. (In fact, you could probably get away with 1/10 second turns or longer.) Any player actions occurring during a single turn should be treated as simultaneous. All messages, at least from the server to the clients, should be tagged with the turn number, so that each client knows which turn each event happens on.

Since your game is using a client-server architecture, you can have the server act as the final arbiter of what happens during each turn, which simplifies some things. Do note, however, that it means that clients must also reconfirm their *own* actions from the server: if a client sends a message saying "I move unit X one tile left", and the server's reply says nothing about unit X moving, the client must assume it did not happen, and possibly cancel any predictive movement animation they may have already started playing.
* Define a consistent order for "simultaneous" events occurring on the same turn, so that each client will execute them in the same order. This order can be anything, as long as it's deterministic and the same for all clients (and the server).

For example, you can first increment all resources (which can be done all at once, if the resource growth in one tile cannot interfere with that in another), then move each player's units in a predetermined sequence, then move NPC units. To be fair to players, you may want to vary the order of unit movement between turns, so that each player gets to go first equally often; this is fine, as long as it's done deterministically (e.g. based on the turn number).
* If you're using floating-point math, do ensure that you're using it in strict IEEE mode. This can slow things down a bit, but that's a small price to pay for consistency between clients. Also make sure no accidental rounding happens during communications (e.g. a client transmitting a rounded value to the server, but still using the unrounded value internally). As noted above, having a protocol to detect and recover from desynchronization is also a good idea, just in case.
> 4 votes

# Answer
You should make your games logic completely independent from real time and essentially make it a Turn-Based. That way you know exactly the turn on which "tiles energy change happens". In your case, each turn is just 1/50th of a second.

That way you have to worry only about player inputs, everything else gets managed by the games logic and completely identical on all clients. Even if the game stalls for a moment, due to Net lag, or extra-complicated calculation, the events are still happening in sync for everyone.
> 3 votes

# Answer
First of all you have to understand that PC float/double math IS NOT deterministic, unless you specify to stricly use IEEE-754 for your calculation (will be slow)

Then this is how i would implement it: the client connect to the server, and sincronize time (take care of the ping latency!) (for long gameplay it may be necessary to resync timestamp/turn)

now, every time a client do an action, it include a timestamp/turn, and is up to the server to reject bad timestamp/turn. Then the server send back the action to the clients, and every time a turn is "closed" (aka server will not accept turn/timestamp so old), server send and end-turn action to clients.

Clients will have 2 "world": one is in sync with the end-turn, the other is calculated starting from end-turn, adding up the action arrived on queue, until the current client turn/timestamp.

because server will accept a bit old action, client may add its own action directly in the queue, so the round trip time over the network will be hidden, at least for your own action.

last thing is to queue more action so you can fill the MTU packet, causing less protocoll overhead; a nice idea is to do that on server, so every end-turn event contain action on queue.

i use this algoritm on a real-time-shooting game, and works fine (with a and without client chaching its own action, but with server ping low as 20/50ms), also every X end-turn server send a special "all client map" packet, to correct drifted values.
> 1 votes

---
Tags: algorithm, networking, client-server, synchronization, strategy
---


# Question
Title: Why is mesh baking causing huge performance spikes?
A couple of seconds into the gameplay on my Android device, I see huge performance spikes caused by "*Mesh.Bake Scaled Mesh PhysX CollisionData*"

In my game, a whole level is a parent object containing multiple ridigbodies with mesh colliders. Every `FixedUpdate()`, my parent object rotates around the player.

Rotating the world causes mesh scaling. Here is the code that handles world rotation.

```
 private void Update()
    {
        input.update();

        Vector3 currentInput = input.GetDirection();

        worldParent.rotation = initialRotation;

        worldParent.DetachChildren();
        worldParent.position = transform.position;
        world.parent = worldParent;

        worldParent.Rotate(Vector3.right, currentInput.x * 50f);
        worldParent.Rotate(Vector3.forward, currentInput.z * 50f);
    }

```

How can I get rid of mesh scaling ? Mesh.Bake physx seems to take effect after some time, is it possible to disable this function ?

The profiler looks like this:

*Bottom-left panel shows data before spikes, the right after*

# Answer
> 1 votes
When initializing the physics components for an actor within the world, PhysX needs to know about the collision geometry. PhysX either generates this geometry at run time, or loads it from a precooked cache. This link has a more detailed description of this. If unity supports pre-cooking your collision geometry, then this would eliminate the spikes caused by this.

https://developer.nvidia.com/sites/default/files/akamai/physx/Docs/Serialization.html#caching-cooked-geometry-data

Also, using primitive collision geometry wont require complex hull generation that is required for complex triangle mesh collision. On top of that, primitive collision checks are usually much faster for primitives such as spheres, capsules, AABB's, and OBB's

# Answer
> 0 votes
(a) How big are your meshes? (b) Are they non-convex manifolds?

...These factors may lead to a high cost in pre-processing. Most games don't need to use their actual meshes for collision (or if they do, their meshes have been designed with the above factors in mind).

Suggest just using a capsule, box or sphere collider -- or collections of these (say, for different limbs). It will save you a lot of time and you'll hardly notice the difference.

---
Tags: android, unity, collision-detection, profiling
---


title: AndEngine GLES 2 Animate Character

text:
# Question
Title: AndEngine GLES 2 Animate Character
I want to animate my character in game. My graphic animator prepare for me three options.

1. Frame-by-frame by this is over 9MB for one animation. With TextureSpriter 4-5MB.
2. Spriter but I can't find how to handle scml in GLES 2.
3. FLA/SWF and this is my best promissing option because size of swf with animation is 1,8 MB. But so far I google that flash is no longer supported in android and it's big issue to use it with AndEngine.

What's more I found this question maybe something is changed since '13.

So I guess I got only option 1. Am I wrong? What do you use to animate?

# Answer
I guess I cannot give you a definite answer, however I could bring some tips to the table.

1. What approach you go for can depend heavily on the quality standards and style you have chosen for your game. Blockbuster titles with a ultra high resolution, framerate and detail standards and with a photorealistic style will most likely be better of with more advanced/high-power engine capabilities than a retro pixelated 8-bit game.
2. I have previously made an animated GIF loader for Android (support for animated gif was lacking back in the day, but I think it is present now). Don't go there. It's slow, takes a lot of processing and limits the quality badly. I kept hitting memory limits that would shut my app down without warning. Ugly.
3. SWF/FLA - Don't go there. See GIF.
4. Use Flash as creative tool but export .PNG? We have a game in the works called astrobabe (click link for video) where all the graphics are hand animated FBF in adobe flash (animator's tool of choice) and later exported to PNG sprite sheets that are loaded. The animations has limited number of frames and sizes to fit in the power of two texture sizes. We also split some textures up in many parts and animate them in code where this makes sense. Our engine for this game is AndEngine (which I cannot recommend anyone to use). Luckily our animator is very technically skilled and manages to keep the sprite sizes within bounds. Loading is done natively with AndEngine, while all animation playback is handled in a thin layer of convenience and simplification we made ourselves on top of Andengine's horrible animation system. This works great, although keeping track of the files is a hassle.
5. There is native support for animating with PNGs in Android. You write some XML that pulls in the right frames at the right position and time to form sequences that can be played back. I have not tried this myself, but I am guessing its much better than the GIF/SWF approaches. The problem is how the formats will be handled by your animator. I am sure there are some export plugins out there that will help you shoehorn some FBF material into a hodgepodge of PNG + XML that works as valid Android resources.
6. There are a myriad of sprite animation libraries and game engines out there all with their own way of handlig and supporting assets in different ways and formats. My latest ventures have been in libgdx, which so far have been awesome. It ha good documentation too. Here is an article on sprite animation in libgdx. And what is awesome about libgdx is that it supports 3d with full model loading capabilities as well, so there are probably ways for you to fake 2d through that. That will give you access to a lot of high-end creative tools in form of 3D software.
7. Good luck!
> 0 votes

---
Tags: java, animation, flash, andengine, spritesheet
---


title: Object-Oriented OpenGL

text:
# Question
Title: Object-Oriented OpenGL
I have been using OpenGL for a while and have read a large number of tutorials. Aside from the fact that a lot of them still use the fixed pipeline, they usually throw all the initialisation, state changes and drawing in one source file. This is fine for the limited scope of a tutorial, but I’m having a hard time working out how to scale it up to a full game.

How do you split your usage of OpenGL across files? Conceptually, I can see the benefits of having, say, a rendering class that purely renders stuff to screen, but how would stuff like shaders and lights work? Should I have separate classes for things like lights and shaders?

# Answer
I think OO OpenGL is not that necessary. It is different when you talk about shader, model, etc class.

Basically you would do game/engine initialization first (and other things). Then you would load textures, models and shaders to RAM (if needed) and Buffer Objects, and upload/compile shaders. After that, you, in your data structure or class of shader, model, have *int* IDs of shaders, model and texture buffer objects.

I think most engines have engine components and everyone of them has certain interfaces. All engines I have looked into have some component such as Renderer or *SceneManager* or both (depends on complexity of game/engine). Than you can have *OpenGLRenderer* class and/or DXRenderer which implement Renderer interface. Then if you have *SceneManager* and *Renderer* you can do some of the following things:

* Traverse *SceneManager* and send each object to *Renderer* for rendering
* Encapsulate upper case in some *SceneManager* method
* Send *SceneManager* to *Renderer* so it handles it

Renderer would probably call object's draw function which would call draw function of each mesh that is composed of and mesh would bind texture object, bind shader, call OpenGL draw function and then unuse shaders, texture and object data buffer objects.

**NOTE: this is just example, you should study *SceneManager* in more detail and analyze your use case to see what is best implementation option**

You would of course, have other components of engine, such as *MemoryManager*, *ResourceLoader* etc, which would take care of both video and RAM memory usage, so they could load/unload certain models/shaders/textures as needed. Concepts for this include memory caching, memory mapping etc etc. There are lot of details and concepts about each components.

Take a look at more detailed description of other game engines, there are a lot of them and their documentation is pretty much available.

But yes, classes make life easier; you should totally use them and remember about encapsulation, inheritance, interfaces, and more cool stuff.
> 6 votes

# Answer
OpenGL has some 'Object' concepts in it already.

For example anything with an id can be through of as an object (There are also things specifically named 'Objects'). Buffers, Textures, Vertex Buffer Objects, Vertex Array Objects, Frame Buffer Objects and so on. With a little work you can wrap classes around them. It also give you a easy way to fall back to old deprecated OpenGL functions if your context doesn't support the extensions. For example a VertexBufferObject could fall back to using glBegin(), glVertex3f(), and so on.

There are a few ways you might need to move away from the traditional OpenGL concepts, for example you probably want to store metadata about the buffers in the buffer objects. For example if the buffer stores vertices. What is the format of the vertices (ie position, normals, texcoords and so on). What primitives it uses (GL\_TRIANGLES, GL\_TRIANGLESTRIP, etc...), size information (how many floats are stored, how many triangles they represent, etc...). Just to make it easy to plug them into the draw arrays commands.

I recommend you look at OGLplus. It's C++ bindings for OpenGL.

Also glxx, that's only for extension loading though.

In addition to wrapping the OpenGL API, you should look at making a slightly higher level one build on top of it.

For example a material manager class that is responsible for all your shaders, loading and using them. Also it would be responsible for transferring properties to them. That way you can just call: materials.usePhong(); material.setTexture(sometexture); material.setColor(). This allows fore more flexibility since you can use newer things like shared uniform buffer objects to just have 1 big buffer containing all the properties your shaders use in 1 block but if its not supported you an fall back to uploading to each shader program. You can have 1 big monolithic shader and swap between different shader models using uniform routines if it's supported or you can fall back to using a bunch of different small shaders.

You can also look at expending on from the GLSL specs for writing your shader code. For example the #include would be incredibly useful and very easy to implement in your shader loading code (there is also an ARB extension for it). You can also generate your code on the fly based on what extensions are supported, for example use a shared uniform object or fall back to using normal uniforms.

Finally you will want a higher level rendering pipeline API that does things like scene graphs, special effects (blur, glow), things that require multiple rendering passes like shadows, lighting and such. And then on top of that a game API that has nothing to do with the graphics API but just deals with objects in a world.
> 2 votes

# Answer
In modern OpenGL you can almost totally seperate rendered object from each other, using different vaos and shader programs. And even the implementation of one object can be separated into many abstraction layers.

For example, if you want to implement a terrain, you could define a TerrainMesh whose constructor creates the vertices and indices for the terrain, and sets them into arraybuffers, and - if you give it an attribute position - it shaderplumbs your data. It should also know how to render it, and it should take care to revert all the context changes it has done to setup the rendering. This class itself should know nothing about the shader program that is going to render it, and nor should it know anything about any other objects in the scene. Above this class you could define a Terrain, which is aware of the shader code, and its job is to create the connection between the shader and TerrainMesh. This should mean getting attribute and uniform positions and loading in textures, and things like that. This class should not know anything about how the terrain is implemented, what LoD algorithm it uses, it is just responsible for shading the terrain. Above this, you could define the non-OpenGL functionality like behivour and collision-detection and such.

Coming to the point, even though OpenGL is designed to be used low-level, you can still build independent layers of abstraction, that let you scale up to apllications with a size of an Unreal game. But the number of layers you want / need really depends on the size of the application you want.

But don't lie to yourself about this size, don't try to mimic Unity's object model in a 10k line application, the result will be a complete disaster. Build the layers gradually, only increase the number of abstraction layers, when it's needed.
> 1 votes

# Answer
ioDoom3 is probably a great starting point, as you can kind of rely on Carmack to follow great coding practice. Also I believe he doesn't use megatexturing in Doom3, so it's relatively straight forward as a render pipe.
> 0 votes

---
Tags: c++, opengl, architecture, objects
---


# Question
Title: How do I deal with timeout detection and recovery in D3D?
What is exactly measured when checking TDR in Windows? What do I need to do in my D3D11 app to tell TDR that long rendering is okay? I've already split the workload into smaller batches, but how do I tell TDR when this batch begins and when it ends?

I know that `IDXGISwapChain::Present` method will do this for me, but is it the only way? Is `ID3D11DeviceContext::Flush` method doing the same thing?

# Answer
By "task" in the TDR docs, I believe they essentially mean "draw call or dispatch call". So if a single draw/dispatch takes over 2 seconds, the OS will assume the GPU/driver is crashed and reset it. AFAIK, you shouldn't get TDRs if the work is split into individual draws/dispatches that take less than 2 seconds each.

Also, in D3D 11.1 (Windows 8.0) there is a flag to disable TDR, which can be specified when you create the device. It's `D3D11_CREATE_DEVICE_DISABLE_GPU_TIMEOUT`, as described on this page.
> 1 votes

# Answer
The best way is to not have a timeout.

TDR is covered at the following MSDN article: http://msdn.microsoft.com/en-us/Library/Windows/Hardware/ff570088%28v=vs.85%29.aspx and is discussed in some detail, including the reasons for it, how it operates, and which registry keys control it.

You can certainly extend the TDR interval beyond the default 2 seconds, but Microsoft themselves advise that:

> You can use the following TDR-related registry keys for testing or debugging purposes only. That is, they should not be manipulated by any applications outside targeted testing or debugging.

In other words, fix whatever is causing a TDR during your testing and ship your program without TDRs.

The reason is that the behaviour is by design: it's to assist with misbehaving programs or drivers that lock up the GPU and cause an unresponsive system. By issuing a TDR the OS will at least be returned to the user in an actual usable state and without requiring a hard reboot.

So if you're getting TDRs you've either (1) got a bad driver, or (2) are doing something that takes an abnormally long time.
> 0 votes

# Answer
According to Windows, if a graphics device takes longer than 2 seconds to perform a task, it is hung. If your program is causing the graphics device to TDR, consider upgrading your driver or breaking up the workload into smaller segments.

There is also some TDR registry keys (linked below). However, these are more for debugging purposes: "You can use the following TDR-related registry keys for testing or debugging purposes only. **That is, they should not be manipulated by any applications outside targeted testing or debugging.**"

When a TDR occurs you will get a DirectX device lost error. To recover, you have to recreate your D3D device.

http://msdn.microsoft.com/en-us/library/windows/hardware/ff570087(v=vs.85).aspx http://msdn.microsoft.com/en-us/library/windows/hardware/jj676805(v=vs.85).aspx (for win8)

http://msdn.microsoft.com/en-us/library/windows/hardware/ff569918(v=vs.85).aspx (tdr related registry keys)
> -1 votes

---
Tags: directx11, windows
---


title: Replacement for XNA Lobby?

text:
# Question
Title: Replacement for XNA Lobby?
I am looking to implement with the Microsoft Windows Live game lobby. Since Microsoft has deprecated XNA, I am wondering if it is still possible to interact with the game lobby they provided in XNA (assuming it is not deprecated as well?).

I am doing this for an engine written in C++

In other words, I am wondering if Microsoft is still offering a game lobby system for developers (for indie developers that is). I am trying to track down the documentation for a possible replacement but I can only find resources for XNA.

If not, are there any good, possibly free alternatives? I have no problem writing my own lobby service but I would rather save the time with an already existing solution.

# Answer
> 1 votes
Some alternatives are GameSpy and SteamWorks.

The latter requires "SteamWorks approval" before you gain access. Both are free.

EDIT: GameSpy will be discontinued on 31th of May, 2014!

---
Tags: c++, networking, multiplayer
---


# Question
Title: Which texture do I bind to when implementing multi-texturing?
I have been having some issues getting multi-texturing to work using OpenGL ES 1.1. I have two PKMs - one with RGB's and one for alphas and I am trying to combine the two as below:

```
            int rgbTexture = textureId[0];

            gl.glActiveTexture(GLES10.GL_TEXTURE0);
            gl.glBindTexture(GLES11.GL_TEXTURE_2D, rgbTexture);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_TEXTURE_ENV_MODE, GLES11.GL_MODULATE);

            ETC1Texture etcTexture = ETC1Util.createTexture(inputStream);
            ETC1Util.loadTexture(GLES11.GL_TEXTURE_2D, 0, 0, GLES11.GL_RGB, GLES11.GL_UNSIGNED_SHORT_5_6_5, etcTexture);

            int alphaTexture = textureId[1];

            gl.glActiveTexture(GLES11.GL_TEXTURE1);
            gl.glBindTexture(GLES11.GL_TEXTURE_2D, alphaTexture);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_TEXTURE_ENV_MODE, GLES11.GL_COMBINE);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_COMBINE_RGB, GLES11.GL_REPLACE);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_SRC0_RGB, GLES11.GL_PREVIOUS);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_OPERAND0_RGB, GLES11.GL_SRC_COLOR);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_COMBINE_ALPHA, GLES11.GL_MODULATE);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_SRC0_ALPHA, GLES11.GL_TEXTURE);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_OPERAND0_ALPHA, GLES11.GL_SRC_ALPHA);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_SRC1_ALPHA, GLES11.GL_PREVIOUS);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_OPERAND1_ALPHA, GLES11.GL_SRC_ALPHA);

            InputStream inputStreamAlpha = fileIO.readAsset(fileName + "_alpha.pkm");
            ETC1Texture etcAlphaTexture = ETC1Util.createTexture(inputStreamAlpha);
            ETC1Util.loadTexture(GLES11.GL_TEXTURE_2D, 0, 0, GLES11.GL_RGB, GLES11.GL_UNSIGNED_SHORT_5_6_5, etcAlphaTexture);

```

One of the problems that I am having is I don't know which texture ID to bind to when rendering this multi-texture and if I should make GL\_TEXTURE0 or GL\_TEXTURE1 active when rendering. The code above is from the load() method within my Texture class. On startup, I load all of the necessary textures using the code above. I then keep a reference to these Texture objects while I still need them and when I want to render them, I bind to the ID of the rgbTexture (as shown above) and I make GL\_TEXTURE0 active. Is this correct? Should I be binding to the alphaTexture's ID? Should GL\_TEXTURE1 be active when rendering? Or both? Or is multi-texturing supposed to happen at render time? Ideally I am looking for a solution that combines these textures into one at startup and then when rendering, I just bind to this one combined texture.

# Answer
> 1 votes
Well, think of texture units (GL\_TEXTURE0, GL\_TEXTURE1), as layers, each texture layer can have any texture assigned to it (texture id). This should be done when rendering and not when loading the textures.

When rendering you need to:

```
for each used texture unit
 Activate texture unit using glActiveTexture;
 glBind the appropriate texture;

Blend the textures using Modulate, Add etc;
And finally draw your object;

```

---
Tags: android, opengl-es, multitexturing
---


# Question
Title: How can I use shaders to make a square have a waving effect?
I'm new to using shaders to do some fancy effects and I'm struggling with them. I'm using DirectX 11 and HLSL. I have this square in the middle of the screen:

It's just a square that I've created using 4 vertices. I want to give it this waving effect on the sides, but I don't know how to do it.

This is for a little 2D game I'm making, so I have an orthogonal projection matrix which is the one I use. View matrix is set to identity.

```
DirectX::XMMATRIX view = DirectX::XMMatrixIdentity();
DirectX::XMMATRIX projection = DirectX::XMMatrixOrthographicOffCenterLH(0.0f, SCREEN_WIDTH, SCREEN_HEIGHT, 0.0f, 0.0f, 1.0f);

```

This is the constant buffer I set each frame, so I can pass a float time variable to the shader:

```
struct constant_buffer {
    DirectX::XMMATRIX  WVP;
    // this value starts in 0 and increases by 1 each frame until 359 degrees
    float time;
};

constant_buffer cbuffer;

```

The shader that I'm currently using is very simple, it just applies the matrix to each vertex to transform it.

```
struct in_pshader
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

cbuffer constant_buffer
{
    float4x4 WVP;
    float time;
};

in_pshader vshader(float4 position : POSITION, float4 color : COLOR)
{
    in_pshader output;

    output.position = mul(position, WVP);
    output.color = color;

    return output;
}

float4 pshader(float4 position : SV_POSITION, float4 color : COLOR) : SV_TARGET
{
    return color;
}

```

I'm guessing there's some sine function involved around, so that's why I decided to pass angles per frame as input. I tried many combinations, but I'm such a newbie and can't get it right. :( Any help on this would be very appreciated.

# Answer
First of all, to create this kind of effect you're going to need more than 4 vertices. You can move the vertex positions around all you like, but a shape made with 4 vertices will only ever be a quadrilateral, not a shape with wavy sides like you've shown. You'll have to subdivide the shape vertically, at least, so that it has enough vertices along each side to make the smooth sine curve. It's not necessary to subdivide it horizontally for the effect you've shown.

Once that's done, it's pretty easy to do this. You'd add a line to your vertex shader like

```
position.x += a * sin(k * position.y + f * time);

```

where a, k, f are some constants you can tweak (they can be hard-coded, or you can put them in your constant buffer). This will move each vertex horizontally (adjusting position.x) depending on both its vertical position (position.y) and the current time.

This should be done before the multiplication by the WVP matrix, assuming you want the distortion to apply in world space as opposed to screen space.
> 3 votes

# Answer
As an alternate solution from vertex tessellation/subdivision, you can also do this in the fragment shader by simply drawing a smaller square within your quad and offsetting the pixels. You will need to resize your geometry to a larger size to make it match your desired result.

For example, in your fragment shader, you have local X,Y coordinates passed in from the vertex shader which range from 0-1. You check to see if they are in range 0.25 to 0.75, and if they aren't, then discard the pixel. To apply the waving effect, you add the sine function to the X coordinate. Depending on the strength of your sine wave, you will need to shrink the square to fit the distorted edges within your drawing area (the quad).

Keep in mind this method may not be as efficient as a subdivided quad, due to more pixels being processed by the GPU to draw the square, ie "overdraw".
> 2 votes

---
Tags: shaders, hlsl, directx11
---


title: How to manage variables and/or data?

text:
# Question
Title: How to manage variables and/or data?
Let's say I have a class A with many constants (over 20) and variables (also around 20). Class B represents a character so it has a lot of constants and variables representing various stats. Class C is GUI class and draw interface showing player his stats. I would like to have also classes for dialogs, items, quests, etc. Working with such a many variables is a lot of pain for me trying to manage it only in code.

How is that type of problems managed in game development? I'm doing an android game primarily so the performance cost should be get under consideration.

Example code that is really annoying and feels bad:

```
Label life, xp, gold, stamina, recovery, score; // etc. Label class is GUI text

void Start()
{
    life.text = Character.instance.Life.ToString();
    xp.text = Character.instance.XP.ToString() + "XP";
    gold.text = Character.instance.Gold.ToString() + "$";
    stamina.text = Character.instance.Stamina.ToString();
    recovery.text = Character.instance.Recovery.ToString();
    score.text = Character.instance.Score.ToString();
    // etc.
}

```

Or even:

```
int level, gold, experience, life; // etc.

void Start()
{
    level = STARTING_LEVEL;
    gold = STARTING_GOLD;
    experience = STARTING_EXPERIENCE;
    life = STARTING_LIFE;
    ...
}

```

# Answer
> 2 votes
Well I am not sure about good practises or standards here, but I do use `Managers`(Mostly `Singletons`) to manage certain aspects of my game. For example, I always have a `GUIManager` class which takes care of all the GUI related stuff for me. It has listener methods for every event, for example when player dies the player script calls `OnPlayerDie()` method on GUIManager, which pops up the message on screen. The change in health is also indicated via `OnHealthChange()` method.

In case you have too much data or UI elements, let other classes which are responsible for updating them, handle them. For example the life of player will be handled by Player class, the GUI Text or UILabel(if using NGUI) will still resides in GUIManager and will be accessed via Singleton calls by Player Class.

Reusing variables via managers is also a way to reduce number of variables.

# Answer
> 0 votes
Your example is exactly what is done, there's no magic way to make it go away, only to maybe to hide it. I don't think it's quite bad. You enter one line of code for each stat.

Another solution would be making some automatic code that would extract values from same named fields. Something like this:

```
class CharacterGui : BaseGui
{
    Label life;
    void Update(Character ch)
    {
        base.ExtractValues(ch); // life here would be auto assigned to value
    }
}
class BaseGui
{
    public ExtractValues(object o)
    {
        // use reflection to find matching fields and extract value from o,
        // call ToString() and assign it to label of the same name in your class
    }
}

```

But here you would need to have some kind of strict naming system, or use Attributes to mark fields:

```
class CharacterGui : BaseGui
{
    [Attribute("health")]
    Label life;
    void Update(Character ch)
    {
        base.ExtractValues(ch); // life here would be auto assigned to value from field "health" of ch
    }
}

```

Either way that seems a much more work and maintenance then just adding a single line of code. Those systems are usually put in place where there's a lot, and I mean a lot of code that will use it, think of million dollar companies with 100 programmers working on it. At those companies it actually can save a lot of time.

I would also suggest that you make your GUI classes not to rely on static vars, but rather take any instance of the class they want to display. That way when you change your mind later and decide that you want 2 characters on the screen, you can easily just reuse the code.

```
Label life, xp, gold, stamina, recovery, score; // etc. Label class is GUI text
void Update(Character ch)
{
    life.text = ch.Life.ToString();
    //...
}

```

# Answer
> 0 votes
I've decided to use dictionary for storing variables in my Character singleton class where key is string for example "life" and value is float value of the key.

Initializing the dictionary is made using readonly string and float arrays where I store in appropriate order string keys and float values (it can be done by using also enum to avoid some string related problems). Adding whole bunch of stats can be done in simple for loop. "Run-time" stats changes are made by using events since it fits rpg game mechanism.

Getting the values is very simple by using C# indexers feature:

```
    Dictionary<string, float> stats = new Dictionary<string, float>();
    public float this[string key]
    {
        get { return this.stats[key]; }
    }

```

And in practice it looks for example like this:

```
print(Character.instance["life"]);    // Will print character life value

```

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