# Question
Title: Is there any way to verify the GPS location data received from client?
The answer to this question may be "NO" but it's quite important so I think I might as well ask.

This should be a problem for all client-server location-aware games where player locations in the world are central to the gameplay. Is there any way we can make sure that the location data that's coming from the client is real (i.e. the player is actually there)?

Working on client-server games, we all know that we should never trust any information coming from the client and therefore all important game logic should be done server-side. However with location information, we MUST receive this from the client. Is there a way to double check this to prevent cheating?

# Answer
You can use an IP geolocation service to obtain an approximate location from where the user is connecting. Compare this with the GPS data received and you can weed out some extreme cases (players connecting though proxy, etc). You can even calculate distances between user logins and if they are too high (say, the location moved 1000 kms between two login attemps in 5 or 10 minutes) notify the user.

However this isn't foolproof and you will cause more than one inconvenience to legitimate players.
> 10 votes

# Answer
There is nothing on the client side which can not be faked, everything somebody has physical access to can be manipulated.

The IP contains routing information and thus hints on the location. But the player just needs a proxy and whoops... the IP hints at a completely different location than the player actually is.

Trust your players, don't give them a reason to try to trick the system in the first place.
> 10 votes

# Answer
You cannot truly verify this information any more than you can truly verify any information created by an external source. So what you want is theoretically impossible. But you can probably make it a bit harder to fake.

For example, on Android phones you have various location providers, such as locating a user by the nearby cellphone masts, Wi-Fi position system, etc. You could require that at least two location providers return similar values in order to trust the more precise of the two.

I would not recommend using IP geolocation; here in the UK it is hopelessly inaccurate since most of us use national ISPs. On a good day geo-targetted ads refer to locations about 20 miles away, and on a bad day they think I am 100 miles away. But you can probably use it to verify the user is in the right country!
> 3 votes

# Answer
No. No way. Not even in theory.
> 1 votes

---
Tags: client-server, security, geolocation
---


# Question
Title: Taking MSAA screenshot using D3DX10SaveTextureToFile()
I have some screenshot code (pasted below) which was working fine until I enabled MSAA. The first time I tried to use this code, it complained that the texture I'm creating needed to match the sample count of the source texture. Fine- my MSAA value is 8 currently, so I set the screenshot texture to a sample count of 8 also.

Now when I try to use the code, it complains:

> ERROR: ID3D10Device::CreateTexture2D: A multisampled Texture2D cannot be bound to certain parts of the graphics pipeline, but must have at least one BindFlags bit set. The following BindFlags bits (0) cannot be set in this case: D3D10\_BIND\_VERTEX\_BUFFER (0), D3D10\_BIND\_INDEX\_BUFFER (0), D3D10\_BIND\_CONSTANT\_BUFFER (0), D3D10\_BIND\_STREAM\_OUTPUT (0)

Note- this happens when I call CreateTexture2D(). However, if I take the hint and try a BindFlag with my created texture (D3D10\_BIND\_RENDER\_TARGET for example) I get the exact same error message when D3DX10SaveTextureToFile() is called.

Here is the code:

```
ID3D10Resource* pScreen;
mpRenderTargetView->GetResource( &pScreen );

HRESULT hr;

D3D10_TEXTURE2D_DESC texDesc;
texDesc.ArraySize = 1;
texDesc.BindFlags = D3D10_BIND_RENDER_TARGET;
texDesc.CPUAccessFlags = 0;
texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
texDesc.Width = (unsigned int)mWindowSize.x;
texDesc.Height = (unsigned int)mWindowSize.y;
texDesc.MipLevels = 1;
texDesc.MiscFlags = 0;
texDesc.SampleDesc.Count = 8;
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D10_USAGE_DEFAULT;

ID3D10Texture2D *texture;
hr = mpD3DDevice->CreateTexture2D( &texDesc, 0, &texture );
mpD3DDevice->CopyResource( texture, pScreen );

char* filename = "TestFile.dds"

D3DX10SaveTextureToFile( texture, D3DX10_IFF_DDS, filename );
texture->Release();
pScreen->Release();

```

I should also mention that I've tried various file formats with no success yet. This function has been a real pain in the butt so if there's a better way of doing this, I'd love to know it!

# Answer
> 2 votes
I imagine it simply doesn't understand multisampled images, I can't think of an image format that supports them.

ResolveSubresource(..) will let you copy from a multisampled source to a non-multisampled target, which you shouldn't have trouble saving.

---
Tags: directx, directx10, screenshot
---


title: How to start with more complex games?

text:
# Question
Title: How to start with more complex games?
I'm a new game developer and I have already finished Pong, Breakout and Snake. I want to start with strategy games, where do I read up on that? What ideas should I wrap my head around? I like games like civilization, master of Orion, etc.

Edit: I use objective-c and cocos2d. My question is more general and broad, for example how would one start with such games, e.g. I want to make a very simplified civ game. I have a tile map, one town and one attack unit. Town gives me x money every turn, i can build more units in town. How do I store said town, units? Do i use classes for them? Where does my combat function go? In units, or in separate entity? Do I use inheritance for digferent units, how do I handle makinf more units in towns? How so I implement turn-based turn? Some sort of state machines? General read about those topics would be nice.

# Answer
Theres a few things I would start looking at:

First you will need to decide on the best structure of the game: One method would be to use a Entity/Component/System Architecture (Here is a link for a great answer from Byte56)

One advantage of this is that your entity is pure data and new units can be added by configuration alone, which means there is no inheritance and any number of units can be added with no code changes.

This also answers another part of your question:

> Where does my combat function go?"

In a Entity system it would be its own system acting on the data within the entity.

To implement turned based one method would be to simply maintain a list of players which are looped through pausing on the Actual Player until they click end turn (or equivalent), then repeat. This would have the advantage of allowing multi-player by adding another player to the list you wait for.

Another point of interest could be path finding, for example A\* path finding Algorithm

As for:

> how do I handle making more units in towns?

I believe the simplest would be to let the town keep track of what it is currently constructing/training and on each turn negate one from its time to build till equals 0.

Hope this helps
> 4 votes

# Answer
I see no problem in simply *starting*. When you have concrete problems, then ask quesitons, at this point there are literary *dozens* of directions you could take...

These more complex projects just last longer and usually require a bit more planning, but there's nothing stopping you from getting an engine (which you already have), making some sketches, and building early prototypes. Remember not to over-think stuff, for example, you might not need an Entity System in your first try (it's a good paradigm in games, but you still need to learn OOP)...

As where you can read up on RTS games, well, as I said, there's no better way to learn than getting your hands dirty. 1 finished game, no matter how simple, is worth more than simply reading articles on the subject.
> 3 votes

# Answer
Depends Entirely on what game you want to make

i would start however by making a tile engine either top down (like a 2D RPG) or side on (like a platformer)

then try getting a player to walk around in it
> 2 votes

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


# Question
Title: PreferredBackBufferWidth/Height from GraphicsDeviceManager not working?
It works fine in other "projects" so it has something to do with project. The project im talking about here has tons of classes but nothing with graphicsdevicemanager other than game1.cs game1.cs starts with

```
    GraphicsDeviceManager graphics;

```

then in public game1()

```
        graphics = new GraphicsDeviceManager(this);
        graphics.PreferredBackBufferWidth = 1024;

```

nope, the game is still 800x600. I have also tried adding graphics.ApplyChanges(); while I dont need it in game1 and would be calling twice, still didnt work.

HOWEVER, if I add

```
        graphics.PreferredBackBufferWidth = 1024;
        graphics.ApplyChanges();

```

to "Initialize" (graphics' init is still from game1) it works

as you can see, I can fix it by going to Initialize and wasting some resource but I wonder why this is happening ? Im sure someone else in my code doesnt interfere.(I have no idea if something like this exist in properties etc. tho)

# Answer
I can think of many different ways that something could be sneaking in and changing the size of your backbuffer. Here are a few guesses:

* Something is hooking `PreparingDeviceSettings` and then overriding `GraphicsDeviceInformation.PresentationParameters.BackBufferWidth`/`Height` during the initial device setup. This seems likely if there is code in the project for configuring multisampling.
* A game component has an `Initialize` method that is doing the same thing as your own "hack" (please don't do this) and doing the equivalent of `ApplyChanges` (it could be calling `GraphicsDevice.Reset` directly, for example).
* The `GraphicsDeviceManager` class adds itself to `Services`. This is how `Game` is able to find it and use it to set up the graphics device in the first place. Perhaps something is using that as a way to go in and mess with it directly?

Probably the best way to determine when this is happening is to hook `GraphicsDeviceManager.PreparingDeviceSettings` or `GraphicsDevice.DeviceResetting` (or perhaps something else) with a blank event that contains a breakpoint (or `Debugger.Break()`). And then inspect the state that is being set up.

The other simple thing to do might be to just full text search your code for the number "600" or "800" and see if that helps you find the code responsible.

Another way, which is slow but will surely find the responsible code, is to step through the entire startup sequence of your game, line-by-line, in the debugger.
> 3 votes

# Answer
Okay there are a couple of basic things i would try.

First: rebuild your solution if you have already not done so.

Second (if that didnt work): try to set the window to full screen, if this works then there is a problem somewhere down your code, look through it and see if you are altering the resolution (you may be doing this in a different object/class dont forget to check them).If you found any resolution changes below the public method then comment them out and try to run again.

If that didnt work then you will have to scontinue debugging, i would recommend quickly setting up an empty project and trying to change the screen resolution, if the same problem occurs there may be something wrong with your ide setup otherwise you know that there is something wrong with your solution and will have to comb through your code to find the culprit. If that doesnt work then copy all of your code into a new project.
> 0 votes

---
Tags: xna, c#
---


# Question
Title: MonoGame: prevent command prompt in windows?
Is there a way to prevent the command prompt from opening in windows when launching the game (via double clicking)?

# Answer
> 2 votes
I am assuming you are using Visual Studio 2010.

Right click on your project (not solution), go to the "Application" tab, under "Output type" change that to "Windows Application"

This is what I do when I want to see a command prompt when running an XNA application.

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


# Question
Title: Android "Activities" --- one or many for games?
I've been learning Android in my spare time, and one of the first things every tutorial/guide will introduce to you is the concept of an "Activity." Everyone loosely defines an Activity as a screen for doing a certain activity.

My question is, how relevant/important is it to have multiple Activities for a game? Are there any guidelines for breaking a game down into multiple Activities? To explain what I mean, let's take a game like Final Fantasy.

In Final Fantasy, you have several different screens that get used over and over and over again:

* The world/dungeon map
* The battle screen
* The equip/skills/items menus

Would each of those be an Activity that you swap back and forth between, or would you redraw the screen within one Activity?

Let's say it is all just one "game" Activity --- this raises other questions, such as, what about a splash screen before the game starts that shows your company logo/name and plays a sound? Should that be considered part of the game Activity, or should it be it's own Activity?

# Answer
> 8 votes
I recently moved into Android development myself. I've got many years of development experience, but decided to wade into the shallow end of Android development.

Which means I was pretty much doing similar things to what you have been doing, but my perspective differs because of experience.

Having said that, I originally started out with the "one screen == one activity" approach, and quickly learned its limitations.

Which works after a fashion. Invariably, I will use some sort of finite state machine, and so activities became the states... simple enough, I thought.

Then I came to the realization that whenever I press the back button, I go to whatever the previous activity is.

This may or may not be a big deal to your game, but consider the following:

You are in the OverworldActivity(using familiar Final Fantasy-esque terminology), wandering around the world, when suddenly you have an encounter and go to the CombatActivity.

If, at this point, you hit the back button, your game goes back to the overworld.

And that is unacceptable to me, and I'm almost certain unacceptable to you.

Yes, you could put handlers into the Activities so that if you are at an invalid activity it sends you to the correct one, but really the better thing to do is to design activities with the "can I safely hit the back button and still have the game play make sense".

So, here's a scheme that is more likely to work for an FF style game:

* MainMenuActivity(has the "start/resume", "instructions", "about")
* HelpActivity (self explanatory)
* AboutActivity (also self explanatory)
* GamePlayActivity(does the world wandering, combat, and most other game aspects that cannot fit into the "go back" scheme, hitting the back button goes back to the MainMenuActivity, which makes sense)
* InventoryActivity(you get here from the GamePlayActivity, and so it makes sense that you "go back" to the GamePlayActivity
* ShopActivity (when you enter a shop/inn/whatever)
* DialogActivity (presuming you can end a conversation at any time by hitting the back button)

And hopefully this helps.

# Answer
> 0 votes
Quoting the Android documentation, "An activity is a single, focused thing that the user can do."

So, for each type of gameplay/menu function, you would want to have a different activity. Your example with Final Fantasy is perfect. As for a splash screen, that seems to be a matter of preference, for example, you could have it integrated with the main menu activity, or have it as a separate one that chains into the main menu.

# Answer
> 0 votes
I may repeat myself, but this was my answer at a similiar question:

> Have a look at Replica Island. It's written by one of the Google engineers. They use different activities for everything. But I think using one activity is way easier! Other games and some of the available game engines do it that way. The downside is that you have to implement behaviour like button presses etc. yourself.

And not only button presses but also the different states a game can be in, like splash screen, menu, playing etc. But since all the mentioned game engines are open source, download them and have a look at their code ;)

Sometimes I think that Google's idea of Activities confuses more than it helps.

---
Tags: java, android, mobile
---


title: Touch point on the near plane

text:
# Question
Title: Touch point on the near plane
I have a matrix created with either `orthoM` or `frustumM` GL function, where the near plane is logically the surface of the tablet. I would like to translate touch locations to their location on the near plane (that is, from device coordinates to the world coordinates).

I assume this is a common enough activity so I'm wondering if a standard API function exists (or simple sequence) which can provide me with this data?

# Answer
Take a look at: gluUnPoroject

From the documentation:

> Map window coordinates to object coordinates. gluUnProject maps the specified window coordinates into object coordinates using model, proj, and view. The result is stored in obj.
> 1 votes

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


# Question
Title: How to make HLSL effect just for lighting without texture mapping?
I created an effect and just want to use lightning but in default effect that XNA create we should do texture mapping or the model appears 'RED', because of this lines of code in the effect file:

```
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
float4 output = float4(1,0,0,1);

return output;
}

```

If I want to see my model, I must do texture mapping by UV coordinates. But my model does not have UV coordinates assigned or its UV coordinates are not exported.

I do texture mapping by this line of code in `vertexshaderfunction`:

```
 output.UV= input.UV

```

When I use BasicEffect I have no problem and model appears correctly.

How can I use "just" lightings in my custom effects?

here is inside of my Model Using BasicEffect

This is my code for drawing with or without BasicEffect inside of my draw() method:

```
    Matrix baseWorld = Matrix.CreateScale(Scale) * Matrix.CreateFromYawPitchRoll(Rotation.Y, Rotation.X, Rotation.Z)
            * Matrix.CreateTranslation(Position);

        foreach(ModelMesh mesh in Model.Meshes)
        {
            Matrix localWorld = ModelTransforms[mesh.ParentBone.Index] * baseWorld;

            foreach(ModelMeshPart part in mesh.MeshParts)
            {
                Effect effect = part.Effect;

                if (effect is BasicEffect)
                {
                    ((BasicEffect)effect).World = localWorld;
                    ((BasicEffect)effect).View = View;
                    ((BasicEffect)effect).Projection = Projection;
                    ((BasicEffect)effect).EnableDefaultLighting();
                }
                else
                {
                    setEffectParameter(effect, "World", localWorld);
                    setEffectParameter(effect, "View", View);
                    setEffectParameter(effect, "Projection", Projection);
                    setEffectParameter(effect, "CameraPosition", CameraPosition);
                }
            }
            mesh.Draw();
        }

```

setEffectParameter is another method that sets effect parameter if i use my custom effect.

# Answer
Effect has Techniques that tells you what vertex shader and pixel shader to use

In your .fx file you will have 1 vertex shader and 2 pixel shader functions, and two techniques

```
technique Colored
{
    pass Pass0
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader  = compile ps_2_0 ColoredPixelShader();
    }
}

technique Texture
{
    pass Pass0
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader  = compile ps_2_0 TexturedPixelShader();
    }
}

```

in Code you will then do

```
if ( /* model has texture coordinates */) // checking this can be complex at runtime but you can find it out from Model.Meshes[].MeshParts[].VertexBuffer.Declaration
{
    Effect.CurrentTechnique = Effect.Techniques["Textured"]
}
else
{
    Effect.CurrentTechnique = Effect.Techniques["Colored"]
}

```

Something similar is done by content pipeline on basic effect when importing Model, and thats where it should happen
> 2 votes

# Answer
Correct me if I wrong, but it looks like you are trying to mimic the BasicEffect shader code into your own shader file.

Microsoft's App Hub provides code for BasicEffect: http://xbox.create.msdn.com/en-US/education/catalog/sample/stock\_effects

From there you can extract what you need, keep in mind that this will be cumbersome as BasicEffect encapsulates a lot of functionality.
> 2 votes

---
Tags: xna, hlsl, lighting, effect
---


title: Invert colors Java rendering

text:
# Question
Title: Invert colors Java rendering
I am making a 2d platformer in java using the slick2d engine. I only use 2 colors: black and white. I want to implement a feature were i invert the colors of certain entities. However i can't find a way to do this. Anyone knows of an easy way or function?

# Answer
> 1 votes
Try this on white one first, add this `Color test = new Color(0f,1f,0f);` then in your render method using your sprite sheet do.

```
spriteSheet.startUse();
test.bind();

//draw sprites

spriteSheet.endUse();

```

If this works then you could simply have a single sprite sheet (of all white) and color it anyway you wish.

Hope it helps

---
Tags: java, rendering, slick
---


# Question
Title: Is it possible to simulate a pause in a game for a fake exhaustive task?
Having windows phone OS 7.1 and it is for better understanding the game pipeline.

`Game.IsFixedTimeStep = true` and `TargetElapsedTime is 60`

The idea was to start a new thread and use `Thread.Sleep()`

```
protected override void Update(GameTime gameTime)
{
    Sleep();

   base.Update(gameTime);
}

bool m_bSleepRunning;
void Sleep()
{
   m_bSleepRunning = true;
   new System.Threading.Thread(
     () =>
               {
                    Thread.Sleep(2000);
                    m_bSleepRunning =false;
               ;}
     ).Start();
   while(m_bSleepRunning)
   {
      //empty cycle
   }
}

```

While debug there is a pause for every update, but the property `gameTime.ElapsedGameTime.TotalMilliseconds` is not updated.

# Answer
By calling `Thread.Sleep()` inside of a new thread the main thread will not sleep and your Update method is not blocked. To achieve the question you asked give this a shot:

```
protected override void Update(GameTime gameTime)
{
    System.Threading.Thread.Sleep(2000);
    base.Update(gameTime);
}

```

If, on the other hand, your objective is to only update something every so often, try something like this:

```
float elapsedTime = 0f;
protected override void Update(GameTime gameTime)
{
    elapsedTime += gameTime.ElapsedGameTime.TotalMilliseconds;

    if(elapsedTime >= 2000)
    {
        elapsedTime = 0;
        // run the code you want to happen every so often here
    }

    base.Update(gameTime);
}

```

The first code block will bring your entire game to a grinding halt for two seconds, this may be what you are trying to do. The second code block will keep your game running, but allow you to execute some code only every two seconds.
> 4 votes

# Answer
`gameTime` is updated by the Game class before `Draw()` and `Update()` are called, not when it is read, so it will not change between the time your new thread starts and when it stops.

Your code,

```
while(m_bSleepRunning)
   {
      //empty cycle
   }

```

Blocks the UI until the thread exits. This defeats the purpose of using a new thread!

If you just want to be notified when a certain time span has elapsed, and respond to that, @NateBross' answer is correct.

If you really need something running in a separate thread that can't be broken into synchronous steps triggered by `Update()`, you might try using a callback:

```
    private void Callback(object sender, EventArgs args)
    {
        /// do whatever you wanted when the thread exits...
        _taskIsRunning=false;
        _taskCompleted=true;
    }

    private event EventHandler ThreadCallback;

    protected override void Initialize()
    {
        ThreadCallback += Callback;
    }

    private bool _startNewTask = false;
    private bool _taskIsRunning=false;
    private bool _taskCompleted=false;

    private void StartTask()
    {
        if (!_taskIsRunning)
        {
            _taskIsRunning = true;
            new Thread(
                () =>
                {

                    /// sleep for two seconds REGARDLESS of update frequency
                    Thread.Sleep(2000);

                    if (ThreadCallback != null)
                        ThreadCallback(this, EventArgs.Empty);

                }
            ).Start();

        }

    }

    protected override void Update(GameTime gameTime)
    {

        if (_startNewTask)
        {
            StartTask();
            _startNewTask=false;
        }

        base.Update(gameTime);

    }

```

*Note that I just threw this together in Notepad++. I doubt that it compiles.*

When you need to start your new task, set `_startNewTask` to `true`. Instead of a delegate, you could shorten things up by just placing the code you want to run at the end of the 2000ms in the Thread() body itself.
> 1 votes

---
Tags: xna
---


# Question
Title: Vector movement in space type game (Mouse rotation)
I'm having an issue with my movement in my 'game' prototype. It's basically not working and admittedly my knowledge with vectors is lacking.

The issue I'm running into is that the ship won't move in the direction of my mouse. (I'm using my mouse as rotation)

Mouse look example video I took yesterday

I would love it if someone could look at my code/Vector math and tell me if they can notice anything I'm doing terribly wrong, I would greatly appreciate it.

```
private Vector2f acceleration;
private Vector2f force;
private Vector2f velocity;
private Vector2f position;
private Image image = null;
private float mass;
private float angle;

//Constructors
public Ship(float xin, float yin) {
    this.mass = 5000; // temp value of mass
    this.angle = 0;

    // Image of the ship
    try {
        this.image = new Image("res/ship.png");
    } catch (SlickException e) {
        e.printStackTrace();
    }

    // Vectors
    position = new Vector2f(xin, yin);
    velocity = new Vector2f(0, 0);
    acceleration = new Vector2f(0, 0);
    force = new Vector2f(0, 0);
}

public void update(Input input, float delta) {
    float mouseX = input.getMouseX();
    float mouseY = input.getMouseY();

    float xDistance = mouseX - (position.x + image.getWidth()/2);
    float yDistance = mouseY - (position.y + image.getHeight()/2);

    angle = (float) (Math.toDegrees(Math.atan2(yDistance, xDistance)) + 90);
    image.setRotation((float)angle);

    if (input.isKeyDown(Input.KEY_W)) {
        this.move(delta);
    } else if (input.isKeyDown(Input.KEY_S)) {
        //this.move(delta);
    } else {
        acceleration = new Vector2f(0, 0);
    }
}

public void move(float delta) {
    /*
     * Acceleration = Force / Mass
     * Velocity += Acceleration * ElapsedTime (delta)
     * Position += Velocity * ElapsedTime (delta)
     */
    System.out.println(delta); //debugging
    //delta = delta/10; //debugging
    //System.out.println(delta); //debugging
    force = angleToVector(angle); // Direction
    force = force.normalise();
    force = force.scale(2);
    acceleration = force.scale(1/mass);

    velocity = velocity.add(acceleration.scale(delta));
    position = position.add(velocity.scale(delta));
}

public Vector2f angleToVector(float angle) {
    return new Vector2f((float)Math.cos(angle), (float)Math.sin(angle));
}

```

If you want to see the full .java for my ship class here's a link.

# Answer
I notice the following:

When you are updating the angles, you are doing the following:

```
angle = (float) (Math.toDegrees(Math.atan2(yDistance, xDistance)) + 90);

```

And when you are moving you are doing this:

```
force = angleToVector(angle);

```

Which means you are *REALLY* doing this:

```
Vector2f((float)Math.cos(angle), (float)Math.sin(angle))

```

To break this down:

1. get mouse vector (correct)
2. convert vector to relative vector based on position of ship (correct)
3. convert vectory to radians with Math.atan2 (correct)
4. use toDegrees to give degrees instead of radians (iffy--see below)
5. add 90 (iffy--see below)
6. store in this.angle (correct)

Then, when moving:

1. take the value in this.angle (correct)
2. don't subtract 90 (fail)
3. don't convert to radians (fail)
4. convert to vector with sin and cos (correct)
5. use the force vector to calculate acceleration (correct)
6. use acceleration to move the ship

So, near as I can see, your problem is failing to do two of your conversions the one way that you do the other way.

One potential fix is to make sure that the conversion is performed the same back and forth, i.e. subtract 90 and convert to radians.

Another potential fix, and the one I recommend, is to not change to degrees and back at all. Instead, do the following:

```
private static final float ANGLE_FACTOR=90.0f;
public void setAngle(float theAngle){angle = theAngle;}
public float getAngle(){return angle;}
public float getImageAngle(){return Math.toDegrees(getAngle()+ANGLE_FACTOR);}

```

You then use this to set the angle

```
setAngle(Math.atan2(yDistance, xDistance));

```

And this for the force vector

```
force = angleToVector(getAngle());

```

And this to set the image angle:

```
image.setRotation(getImageAngle());

```

Alternately, you could also cache the image angle at the same time that you set the angle itself.

Third and final option: normalize the vector from the mouse coordinates (i.e. divide by the length of the vector, if it is not zero), calculate the image angle from that, then you don't have so many conversions all over the place.
> 2 votes

---
Tags: java, physics, vector, rotation, slick
---


title: unity3d camera movment problem

text:
# Question
Title: unity3d camera movment problem
when i turn the camera with

```
var tspeed:float=2.0;

function Start () {

}

function Update () {
if(Input.GetButtonDown("tleft")){
transform.Rotate(0, tspeed* Time.deltaTime, 0);
}
if(Input.GetButtonDown("tright")){
transform.Rotate(0, -tspeed* Time.deltaTime, 0);
}

}

```

it works when pressing the button once but when i hold it it dosnt turn any more and i have to press the button again.how to make it turn when i hold the key?

im using javascript.

# Answer
Use `Input.GetButton("tleft")` instead.

`GetButtonDown` will return true in one update, after the user has pressed the key down. It *won't* return true again until the user releases the key and presses it again.

`GetButton`, however, will be true in each update as long as the user has the key held down during that frame.
> 3 votes

# Answer
Input.GetButtonDown is fired during the frame when user pressed the button. The function return true only one time when user pressed it.

From the Unity Script Reference: Input.GetButtonDown()

> Returns true during the frame the user pressed down the virtual button identified by You need to call this function from the Update function, since the state gets reset each frame. It will not return true until the user has released the key and pressed it again.

You can do something like this:

```
var rightButtonDown= false;
var leftButtonDown= false;

function Update(){
    if(rightButtonDown){
        //rotate...
    }

    if(leftButtonDown){
        //rotate...
    }

    if(Input.GetButtonDown("tleft")){
        leftButtonDown= true;
    }
    else if (Input.GetButtonUp("tleft")){
        leftButtonDown= false;
    }

    if(Input.GetButtonDown("tright")){
        rightButtonDown= true;
    }
    else if (Input.GetButtonUp("tright")){
        rightButtonDown= false;
    }
}

```

**EDIT**

I've made a huge mistake in my previous explanation.

GetButtonDown() is fired only during one frame when the button is pressed as well for GetButtonUp() when the button is released. So to know if the button is hold or not, you have to check state changes when GetButtonDown() or GetButtonUp() are true.

For example, you have a variable "buttonDown" wich is a bool(true, the button is down / false, the button is up). When GetButtonDown() return true, you can assume that the button is hold by user. So you assign true to "buttonDown" and you only change the value of "buttonDown" when GetButtonUp() return true.
> 1 votes

---
Tags: unity
---


# Question
Title: Quaternion dfference + time --> angular velocity (gyroscope in physics library)
I am using Bullet Physic library to program some function, where I have difference between orientation from gyroscope given in quaternion and orientation of my object, and time between each frame in milisecond. All I want is set the orientation from my gyroscope to orientation of my object in 3D space. But all I can do is set angular velocity to my object. I have orientation difference and time, and from that I calculate vector of angular velocity \[Wx,Wy,Wz\] from that formula: W(t) = 2 * dq(t)/dt * conj(q(t))

My code is:

```
btQuaternion diffQuater = gyroQuater - boxQuater;
btQuaternion conjBoxQuater = gyroQuater.inverse();
btQuaternion velQuater = ((diffQuater * 2.0f) / d_time) * conjBoxQuater;

```

And everything works well, till I get:

1\> rotating around Y axis, angle about 60 degrees, then I have these values in 2 critical frames:

```
x: -0.013220    y: -0.038050    z: -0.021979    w: -0.074250    - diffQuater
x: 0.120094    y: 0.818967    z: 0.156797    w: -0.538782    - gyroQuater
x: 0.133313    y: 0.857016    z: 0.178776    w: -0.464531    - boxQuater
x: 0.207781    y: 0.290452    z: 0.245594    - diffQuater -> euler angles
x: 3.153619    y: -66.947929    z: 175.936615    - gyroQuater -> euler angles
x: 4.290697    y: -57.553043    z: 173.320053    - boxQuater -> euler angles
x: 0.138128    y: 2.823307    z: 1.025552    w: 0.131360    - velQuater
d_time: 0.058000

x: 0.211020    y: 1.595124    z: 0.303650    w: -1.143846    - diffQuater
x: 0.089518    y: 0.771939    z: 0.144527    w: -0.612543    - gyroQuater
x: -0.121502    y: -0.823185    z: -0.159123    w: 0.531303    - boxQuater
x: nan    y: nan    z: nan               - diffQuater -> euler angles
x: 2.985240    y: -76.304405    z: -170.555054    - gyroQuater -> euler angles
x: 3.269681    y: -65.977966    z: 175.639420    - boxQuater -> euler angles
x: -0.730262    y: -2.882153    z: -1.294721    w: 63.325996    - velQuater
d_time: 0.063000

```

2\> rotating around X axis, angle about 120 degrees, then I have these values in 2 critical frames:

```
x: -0.013045    y: -0.004186    z: -0.005667    w: -0.022482    - diffQuater
x: -0.848030    y: -0.187985    z: 0.114400    w: 0.482099    - gyroQuater
x: -0.834985    y: -0.183799    z: 0.120067    w: 0.504580    - boxQuater
x: 0.036336    y: 0.002312    z: 0.020859    - diffQuater -> euler angles
x: -113.129463    y: 0.731925    z: 25.415056    - gyroQuater -> euler angles
x: -110.232368    y: 0.860897    z: 25.350458    - boxQuater -> euler angles
x: -0.865820    y: -0.456086    z: 0.034084    w: 0.013184    - velQuater
d_time: 0.055000

x: -1.721662    y: -0.387898    z: 0.229844    w: 0.910235    - diffQuater
x: -0.874310    y: -0.200132    z: 0.115142    w: 0.426933    - gyroQuater
x: 0.847352    y: 0.187766    z: -0.114703    w: -0.483302    - boxQuater
x: -144.402298    y: 4.891629    z: 71.309158    - diffQuater -> euler angles
x: -119.515343    y: 1.745076    z: 26.646086    - gyroQuater -> euler angles
x: -112.974533    y: 0.738675    z: 25.411509    - boxQuater -> euler angles
x: 2.086195    y: 0.676526    z: -0.424351    w: 70.104248    - velQuater
d_time: 0.057000

```

2\> rotating around Z axis, angle about 120 degrees, then I have these values in 2 critical frames:

```
x: -0.000736    y: 0.002812    z: -0.004692    w: -0.008181    - diffQuater
x: -0.003829    y: 0.012045    z: -0.868035    w: 0.496343    - gyroQuater
x: -0.003093    y: 0.009232    z: -0.863343    w: 0.504524    - boxQuater
x: -0.000822    y: -0.003032    z: 0.004162    - diffQuater -> euler angles
x: -1.415189    y: 0.304210    z: -120.481873    - gyroQuater -> euler angles
x: -1.091881    y: 0.227784    z: -119.399445    - boxQuater -> euler angles
x: 0.159042    y: 0.169228    z: -0.754599    w: 0.003900    - velQuater
d_time: 0.025000

x: -0.007598    y: 0.024074    z: -1.749412    w: 0.968588    - diffQuater
x: -0.003769    y: 0.012030    z: -0.881377    w: 0.472245    - gyroQuater
x: 0.003829    y: -0.012045    z: 0.868035    w: -0.496343    - boxQuater
x: -5.645197    y: 1.148993    z: -146.507187    - diffQuater -> euler angles
x: -1.418294    y: 0.270319    z: -123.638245    - gyroQuater -> euler angles
x: -1.415183    y: 0.304208    z: -120.481873    - boxQuater -> euler angles
x: 0.017498    y: -0.013332    z: 2.040073    w: 148.120056    - velQuater
d_time: 0.027000

```

The problem is the most visible in diffQuater -\> euler angles vector. Can someone tell me why it is like that? and how to solve that problem?

All suggestions are welcome.

# Answer
Ahh! Seeing the values, now I see what's going on.

The big subtlety with quaternions is that every rotation has *two* different representations by quaternions; if q is the quaternion representation of a given rotation, then -q represents the same rotation. For whatever reason, as you transition across the thresholds you've indicated, your gyro quaternion is 'flipping' — it's still representing the same rotation but it's using the other quaternion to do so. You can see that while it's now radically different from boxQuater, it's very very close to the negative of boxQuater; blindly taking the difference between the two, then, is resulting in a huge quaternion rather than the very small difference you should see.

The fix, fortunately, is straightforward; since boxQuater and gyroQuater are both (approximately) unit quaternions and since both are supposed to be very near each other, their dot product should be very close to 1. Try computing the dot product of the two before executing your delta and angular-velocity code. If you find the dot product to be close to -1 (in fact, if it's negative at all), then simply negate gyroQuater — replace it by -gyroQuater — before you compute your value for diffQuater.
> 3 votes

# Answer
You are computing the derivative of a quaternion function using `(q(t+Δt) - q(t)) / Δt`. This may lead to accuracy issues because the orientation difference between two quaternions would be better represented by dividing two quaternions.

Unlike usual functions, where the values of the derivative can be summed over time in order to get the real value of the function, unit quaternions are multiplied over time.

So if you have two quaternions for `q(t)` and `q(t+Δt)`, an approximation of the derivative better than `(q(t+Δt) - q(t)) / Δt` is `exp(log(q(t+Δt) / q(t)) / Δt)`.

Your code should therefore be:

```
btQuaternion diffQuater = gyroQuater * boxQuater.inverse();
btQuaternion conjBoxQuater = boxQuater.inverse();
btQuaternion velQuater = 2.0f * exp(log(diffQuater) / d_time) * conjBoxQuater;

```

If you do not have exponential and logarithm functions for your quaternion class, you may implement them using the standard definitions from Wikipedia.

**Edit**: reword to make it clear the initial code was not really incorrect
> 5 votes

# Answer
Thank you guys for the last help, but I moved to PhysX instead of Bullet, and now I have to calculate Torque instead of AngularVelocity. Unfortunately that is more complicated than last one for me :(

I've found some help in here:

http://answers.unity3d.com/questions/48836/determining-the-torque-needed-to-rotate-an-object.html

but not exactly. I have 2 Quaternions, not points(?), and now angularVelocity to rotate between each physic update, and things like: rigidbody.inertiaTensorRotation rigidbody.inertiaTensor;

Is there some way to calculate torque which I need to add to my object?

I have tried something like (from above link):

```
var q : Quaternion = transform.rotation * rigidbody.inertiaTensorRotation;
var T : Vector3 = q * Vector3.Scale(rigidbody.inertiaTensor, (Quaternion.Inverse(q) * angVelocity));
rigidbody.AddTorque(T * 0.01, ForceMode.Impulse);

```

But it seems not work for me, I mean my object does not stop in right place, but starts to jiggle at the end of the move. Even when I multiply Torque by some fraction and add AngularDrag to hight value to rigidbody.

Can you help me with that?
> 0 votes

---
Tags: opengl, 3d, physics
---


# Question
Title: FPS reticule image scaling with resolution problem
I am running into a problem when I set the resolution of my screen and the objects in the HUD. When an increase of resolution happens the reticule image becomes bigger, when I want it to stay the same. Anyone got any tips?

Thanks in advice.

# Answer
You can draw the reticule by using a percentage of the width and height of your resolution.

For example if you want the reticule to be a 5% size:

```
Resolution  | Reticule Size
1024 x 768  | 51.2 x 38.4
1280 x 1024 | 64 x 51.2

```

So the size of the reticule will change depending on the resolution, but it would look the same to you.
> 2 votes

---
Tags: screen, resolution
---


title: OpenGL UBO Query

text:
# Question
Title: OpenGL UBO Query
I'm using 3 'types' of UBOs in my application: per-scene camera parameters, per-material parameters and per-object transform parameters.

I've used glUniformBlockBinding to assign the camera parameters to binding point 1, and the per-object parameters to binding point 2 - these are shared 'global' UBOs.

Each material needs it's own UBO to store the material parameters. Should I be using successive binding points for each material UBO - 3, 4, 5 etc?

# Answer
You should put all materials in the same binding point. You don't bind every material you could ever use *at the same time*; you bind them as you need them.

Just as you don't bind every texture you could ever possibly need all at once. When rendering model A, you bind the textures and UBOs that model A needs, then when rendering model B, you bind the ones that it needs.
> 1 votes

---
Tags: c++, opengl
---


title: Simplex Noise flat land and hills

text:
# Question
Title: Simplex Noise flat land and hills
I'm using the simplex noise to create Minecraft like terrain. I can only achieve hills like this.

Does anyone know how to use simplex to make more dynamic landscapes?

# Answer
One way to achieve this is to have an additional layer of noise (2D) that controls the height of your current noise. This second layer should be scaled larger to give slower transitions between terrain types. The noise you have now defines the bumpy-ness, this second layer is kind of like a scale that will flatten out or exaggerate the bumpy-ness.
> 9 votes

---
Tags: directx, procedural-generation, terrain, perlin-noise
---


# Question
Title: How to make an arrow land at a specific position in 3D world space
In my game when I click with the mouse on the terrain somewhere, I'd like the player to fire an arrow to that position in a parabolic fashion.

The arrow has a position, acceleration and velocity all using 3D vectors. I looked at the Trajectory of a projectile article on wikipedia, but I don't know how to apply it in my situation as it explains 2D mathematics. I was wondering if there's a solution for 3D vectors? Any good resources perhaps related to the 3D situation?

# Answer
> 12 votes
To expand on Kylotan's comment, You can use the 2D formulas in 3D. Assuming Y is up:

calculate the position of the target in X'Y'Z' space, where the X' axis is parallel to the arrow flight direction, Y' axis is up, and Z' is perpendicular to the X' and Y' axes.

Once you have X' and Y' calculated, you can convert back to real XYZ-space

**Example**

An archer is at (1,0,1). He wants to shoot an arrow to (4,0,5). We take X' to be the unit vector (0.6, 0, 0.8) since it points directly from the source to destination point. We then take Z' to be (-0.8, 0, 0.6) because it is a perpendicular, but since the arrow doesn't move in the Z' axis, we will ignore it. Your problem is now figuring out how to shoot an arrow from (0,0) to (0,5) in X'Y' space.

.. do 2D calculations here. Note that you'll probably want parametric functions of X' and Y' in terms of ***t***, the time variable.

One way to abstract the conversion between the two coordinates is to use a transform matrix.

```
let archer = Vector3d(1.0,0.0,1.0)
let target = Vector3d(4.0,0.0,5.0)
let travel = target - archer
let transform = Matrix4d.CreateTranslation(-archer) *
                Matrix4d.CreateRotationY(Math.Atan2(travel.Z,travel.X))
Vector3d.Transform(archer, transform) // transforms archer to (0,0,0)
Vector3d.Transform(target, transform) // transforms target to (5,0,0)

```

when we convert back from **X'Y'Z'** to **XYZ**, this is simply a reverse linear transformation.

```
let inverse = Matrix4d.Invert(transform)
Vector3d.Transform(Vector3d.Zero, transform) // transforms (0,0,0) to (1,0,1)

```

---
Tags: projectile-physics, trajectory
---


# Question
Title: Stuck in an infinite recursion in Minesweeper
I am trying to build a simple minesweeper game. The game gets stuck in an infinite recursion whenever a user clicks on a tile which is not a mine...

I have used the following function code for the click event..

When a user clicks on a tile which is not a mine, its adjacent tiles are to be checked for a mine and the process repeats.... I have used a recursive function which disables the tiles for which adjacent tile is not a mine...

```
  protected void set_text_of_button(Button btn)
  {
      //all these objects specify the location of adjacent tiles
      Block Top, Top_Left, Top_Right, Left, Right, Bottom, Bottom_Left, Bottom_Right;

      //code to specify the location of adjacent tiles...

      //if adjacent tile is a mine then display the total number of tiles....
      //recursive function should end in this if part..

      else
      {
      //recursive calls for all the adjacent tiles..

              if (Top != null && !Top.Mine)
                  set_text_of_button(Top.btn);         //recursive call
              if (Top_Left != null && !Top_Left.Mine)
                  set_text_of_button(Top_Left.btn);
              if (Top_Right != null && !Top_Right.Mine)
                  set_text_of_button(Top_Right.btn);
              if (Left != null && !Left.Mine)
                  set_text_of_button(Left.btn);
              if (Right != null && !Right.Mine)
                  set_text_of_button(Right.btn);
              if (Bottom.btn != null)
                  set_text_of_button(Bottom.btn);
              if (Bottom_Left.btn != null)
                  set_text_of_button(Bottom_Left.btn);
              if (Bottom_Right.btn != null)
                  set_text_of_button(Bottom_Right.btn);

      }
  }

```

can the following code be implemented or is there a better algorithm to perform the task...

# Answer
> 8 votes
I can't tell from your (lack of) code, but you are probably just missing a stop to make sure that you don't handle tiles which have already been handled. At the top of the function you should put something like:

```
if(thistile.hasbeenhandled){
    return;
}
else{
    thistile.hasbeenhandled=true;
}

```

Otherwise any two adjacent tiles that are to display empty will keep on asking one another to update.

# Answer
> 5 votes
eBuisiness's answer is correct. But you're setting the `HasBeenHandled` flag *after* trying to update all the neighbors which then causes a stack overflow. You should instead set the flag before doing anything else.

EDIT: You've also made typos in the `if` statements.

```
  if (Bottom.btn != null)
      set_text_of_button(Bottom.btn);
  if (Bottom_Left.btn != null)
      set_text_of_button(Bottom_Left.btn);
  if (Bottom_Right.btn != null)
      set_text_of_button(Bottom_Right.btn);

```

should be

```
  if (Bottom != null)
      set_text_of_button(Bottom.btn);
  if (Bottom_Left != null)
      set_text_of_button(Bottom_Left.btn);
  if (Bottom_Right != null)
      set_text_of_button(Bottom_Right.btn);

```

Also, you'll need to stop this habit of initializing variables by allocating dummy objects. It is better to assign `null` than create a new object you're not going to use. For example, your `find_by_coordinates` function would be better written as

```
  protected Block find_by_coordinates(int x,int y)
  {
      Block return_value = null;
      foreach (Block blk in arr_buttons)
      {
          if (blk.x == x && blk.y == y)
          {
              return_value = blk;
              break;
          }
      }
      return return_value;
  }

```

Now, when the coordinate has no button a null value is returned instead of a dummy `Block` object which was leading to `NullReferenceException`s because the program was trying to work with these dummy objects.

# Answer
> 0 votes
Your code is ok. I've created my own minesweeper for fun and did the same thing. However I would suggest leaving out the corner tiles ( the adjacent ones ) out. This will make it easier for you to create your algorithm. So instead of 8 tiles it will only check 4.

Basically the easiest way to make your check up stop is to add something to an array, and while this array is not empty, do more check ups:

```
click tile

 > tile is safe? > add to openList ( an array)
 > else gameover

  -while openList is not empty
    -pop tile in array and check adjacent tiles.
     -for every adjacent is safe add to array.

```

The while loop will automatically stop if the openList is empty. For every tile added to the openlist you also remove its click mechanic.

---
Tags: c#, algorithm, windows-forms, minesweeper
---


title: interaction with WinForm and Xna

text:
# Question
Title: interaction with WinForm and Xna
Okay, this is may be very simple. I embedded my XNA project in WinForms through "this tutorial" and it works fine even with XNA 4. Now I have a 3D CoilSpring object and the number of loops for this coil needs to be determined by the user. I'm using a txtBox for this. However when I run the project it only gets the default value of txtBox and I want to update it when the user changes its value.

# Answer
> 1 votes
You can use databinding. For instance if you have an object with a property `NumberOfLoops` which determines the number of loops being drawn:

```
class CoilSpring
{
    int NumberOfLoops { get; set; }
}

```

You can link that property to the value of the textbox doing something like this, for example on the form load event:

```
textbox.DataBindings.Add("Text", coil, "NumberOfLoops");

```

This way the value of `NumberOfLoops` updates automatically whenever you write in the textbox, but not the other way around. If you need changes to happen in *both* directions, you would need to implement the `INotifyPropertyChanged` interface on the `CoilSpring` class (example).

In general, I find this easier than making all the connections manually which requires a lot of boilerplate code to make it work both ways (especially as the number of properties increases), and have been using it all over my editor.

# Answer
> 0 votes
You can do this the 'standard winforms way' by subscribing to the textbox's `TextChanged` event, this way you get a message every time the text is changed, see this MSDN article.

You can also do this by placing the following code in your game's update loop:

```
String prevText; //place this variable outside the update method in the class

if(!textBox.Text.Equals(prevText)){
    if(textBox.Text.Equals(answer)){
       //You win!
    }
    else
    {
        //Incorrect, try again
    }
    prevText = textBox.Text;
}

```

# Answer
> 0 votes
Okay thank you for your helps. Just wanted to say I changed my method and instead of embedding the XNA in WinForm, I embedded WinForm controls in XNA and used the idea from "This LinK" and also created a picture box to show my XNA project window like what I defined from the tutorial mentioned in my question, and then everything works great. thank anyway!

---
Tags: xna-4.0, windows-forms
---


# Question
Title: Most common way to obtain textures for 3D models?
I'm getting into basic 3D modelling and am attempting to texture my model. I'm aware of UV mapping and some similar texturing tools, but I'm not sure how the majority of CG artists obtain their 3D models. When creating realistic models, do they take photos of what they're making a model of and then use those, create multiple textures in Photoshop and then apply those to the model (as in a skin texture and a clothes textures and so on). Also, when creating cartoon-style models, is the method the same? Or do they use different tools, such as Illustrator.

Thanks in advance.

# Answer
> 7 votes
First of all, you should be aware that there are several textures that might be applied to a model. The most common one is the diffuse-map (color, sometimes including alpha), in modern games you'll also find normal-maps (bump-map), specular-maps (amount of specular reflection) etc.

There are different processes to obtain these textures, but generally these have to be made specifically for the model at hand (as the texture has to fit the UV layout) and can't be downloaded or purchased somewhere (unless you buy a model with the texture).

A common workflow looks like this: You create a mesh with lots of details, commonly with a sculpting tool. Ideally your sculpting base-mesh or starting mesh is the low-poly mesh that meets the requirements of your game (amount of triangles).

Then you unwrap the mesh. There are even specialized tools (like UVLayout) that are very good at unwrapping meshes with minimal distortion and making optimal use of the texture-space (packing).

So when you have the UV layout and the model, it's time to create the texture(s). The normal map usually looks like shown in the following image (surface normals are encoded in the RGB colorspace):

It's very hard to create such a texture by hand, therefore it's usually obtained by baking the high-res mesh to the texture-space of the low-res mesh.

Baking texture is a process that's generally useful to get a good starting point for your textures. A common approach is to bake an ambient occlusion map. It will look like this (image © vitamin3d):

This already gives you a great starting-point for your diffuse texture. The process to create the texture is very different from artist to artist and also dependent on the type of texture you need. I think it's safe to say that Photoshop is widely used, in combination with a digital tablet. Sometimes textures are entirely painted, sometimes they are based off photographic imagery.

In case of my avatar image, I decided to print out the UV layout, paint the texture by hand (pencil, felt-tip marker) and scan it back in.

As you can see, there are lots of different ways to create textures, but there's usually a lot of work (and skill) involved in creating good textures. Since the textures also have to match the style/mood of your game, they should be crafted for your game.

# Answer
> 4 votes
Usually in cartoon styled 3D, the texture is made entirely in photoshop after tweaking vertices for the UV map. Honestly though this exactly how it works, you get a bunch of stock photos (or take them yourself) and edit them in photoshop to make them work better for 1. your style of art, 2. most (all) real life things (mainly natural) don't tile perfectly

getting graphics to tile isn't hard, but it takes a while and a bit of fine tuning. It's the things you make BIG edits on that make it hard. Like where skin connects to skin, or where you have weird stretching due to the vertice tweaks. I know it's also really cliche to say, but when the texture looks good, it looks good... You essentially just tweak the model UV points and the texture itself to make it look good. It's a good idea to keep textures nice and clean as well, but doesn't necessarily matter if the texture matches all your other games art.

That is one important note as well. A single texture can throw off game art if it looks completely different. It's always great to look at your model (after texturing) in comparison/in the same scene as, your games other assets.

# Answer
> 1 votes
You can also directly paint your models but unless your as good a paint artist that you are a texture artist, you wont really get anywhere. Texturing might seem like the long road but remember not all textures need to be hand created. Some are imported pictures or slices of bits and pieces of realism and fake portions.

# Answer
> 0 votes
I am using webpages such as http://www.cgtextures.com/ or http://www.filterforge.com/

With little post processing in PS that images usually fits every use I need

---
Tags: 3d, textures
---


# Question
Title: What is the most efficient container to store dynamic game objects in?
I am making a first person shooter and I know about about a lot of different container types but I would like to find the container that is the most efficient for storing dynamic objects that will be added and deleted from the game quite frequently. EX-Bullets.

I think in that case it would be a list so that the memory is not contiguous and there is never any re sizing that is going on. But then I am also contemplating using a map or set. If anyone has any helpful information I would appreciate it.

I am writing this in c++ by the way.

Also I came up with a solution that I think will work.

To start off I am going to allocate a vector of a big size.. say 1000 objects. I am going to keep track of the last added index in this vector so that I know where the end of the objects are. Then I will also create a queue that will hold the indices of all objects that are "deleted" from the vector. (No actual deleting will be done, I will just know that that slot it free). So if the queue is empty I will add to the last added index in the vector + 1, else I add to the index of the vector that was at the front of the queue.

# Answer
> 36 votes
The answer is always to use an array or std::vector. Types like a linked list or a std::map are usually absolutely *horrendous* in games, and that definitely includes cases like collections of game objects.

You should store the objects themselves (not pointers to them) in the array/vector.

You *want* contiguous memory. You really really want it. Iterating over any data in non-contiguous memory imposes a lot of cache misses in general and removes the ability for the compiler and CPU to do effective cache prefetching. This alone can kill performance.

You also want to avoid memory allocations and deallocations. They are very slow, even with a fast memory allocator. I've seen games get a 10x FPS bump by just removing a few hundred memory allocations each frame. Doesn't seem like it should be that bad, but it can be.

Lastly, most data structures that you care about for managing game objects can be far more efficiently implemeted on an array or a vector than they can with a tree or a list.

For instance, for removing game objects, you can use swap-and-pop. Easily implemented with something like:

```
std::swap(objects[index], objects.back());
objects.pop_back();

```

You could also just mark objects as deleted and put their index on a free list for the next time you need to create a new object, but doing the swap-and-pop is better. It lets you do a simple for loop over all live objects with no branching aside from the loop itself. For bullet physics integration and the like, this can be a significant performance boost.

More importantly, you can find objects with a simple pair of table lookups from a stable unique is using the slot map structure.

Your game objects have an index in their main array. They can be very efficiently looked up with just this index (much faster than a map or even a hash table). However, the index is not stable due to the swap and pop when removing objects.

A slot map requires two layers of indirection, but both are simple array lookups with constant indices. They are *fast*. Really fast.

The basic idea is that you have three arrays: your main object list, your indirection list, and a free list for the indirection list. Your main object list contains your actual objects, where each object knows its own unique ID. The unique ID is composed of an index and a version tag. The indirection list is simply an array of indices to the main object list. The free list is a stack of indices into the indirection list.

When you create an object in the main list, you find an unused entry in the indirection list (using the free list). The entry in the indirection list points to an unused entry in the main list. You initialize your object in that location, and set its unique ID to the index of the indirection list entry you chose and the existing version tag in the main list element, plus one.

When you destroy an object, you do the swap-and-pop as normal, but you also increment the version number. You then also add the indirection list index (part of the object's unique ID) to the free list. When moving an object as part of the swap-and-pop, you also update its entry in the indirection list to its new location.

Example pseudo-code:

```
Object:
  int index
  int version
  other data

SlotMap:
  Object objects[]
  int slots[]
  int freelist[]
  int count

  Get(id):
    index = indirection[id.index]
    if objects[index].version = id.version:
      return &objects[index]
    else:
      return null

  CreateObject():
    index = freelist.pop()

    objects[count].index = id
    objects[count].version += 1

    indirection[index] = count

    Object* object = &objects[count].object
    object.initialize()

    count += 1

    return object

  Remove(id):
    index = indirection[id.index]
    if objects[index].version = id.version:
      objects[index].version += 1
      objects[count - 1].version += 1

      swap(objects[index].data, objects[count - 1].data)

```

The indirection layer allows you to have a stable identifier (the index into the indirection layer, where entries do not move) for a resource that can move during compaction (the main object list).

The version tag allows you to store an ID to an object that might be deleted. For example, you have the id (10,1). The object with index 10 is deleted (say, your bullet hits an object and is destroyed). The object in that location of memory in the main object list then has its version number bumped, giving it (10,2). If you try to look up (10,1) again from a stale ID, the lookup returns that object through index 10, but can see that the version number has changed, so the ID is no longer valid.

This is the absolute fastest data structure you can have with a stable ID that allows objects to move in memory, which is important for data locality and cache coherence. This is faster than any implementation of a hash table possible; a hash table at the very least needs to calculate a hash (more instructions than a table lookup) and then has to follow the hash chain (either a linked list in the horrible case of std::unordered\_map, or an open-addressed list in any not-stupid implementation of a hash table), and then has to do a value compare on each key (no more expensive, but possible less expensive, than the version tag check). A very good hash table (not the one in any implementation of the STL, as the STL mandates a hash table that optimizes for different use cases than you game about for a game object list) might save on one indirection, but wil be a larger bloated structure that you can't iterate over at maximum efficiency, and loses out in real-world performance for use cases like this one.

There are various improvements you can make to the base algorithm. Using something like a std::deque for the main object list, for instance; one extra layer of indirection, but allows objects to be inserted into a full list without invalidating any temporary pointers you've acquired from the slotmap.

You can also avoid storing the index inside the object, as the index can be calculated from the object's memory address (this - objects), and even better is only needed when removing the object in which case you already have the object's id (and hence index) as a parameter.

Apologies for the write-up; I don't feel it's the clearest description it could be. It's late and it's difficult to explain without spending more time than I have on code samples.

# Answer
> 13 votes
fixed size array (linear memory)
with internal free list (O(1) alloc/free, stable indicies)
with weak reference keys (reuse of slot invalidates key)
zero overhead dereferences (when known-valid)

```
struct DataArray<T>
{
  void Init(int count); // allocs items (max 64k), then Clear()
  void Dispose();       // frees items
  void Clear();         // resets data members, (runs destructors* on outstanding items, *optional)

  T &Alloc();           // alloc (memclear* and/or construct*, *optional) an item from freeList or items[maxUsed++], sets id to (nextKey++ << 16) | index
  void Free(T &);       // puts entry on free list (uses id to store next)

  int GetID(T &);       // accessor to the id part if Item

  T &Get(id)            // return item[id & 0xFFFF];
  T *TryToGet(id);      // validates id, then returns item, returns null if invalid.  for cases like AI references and others where 'the thing might have been deleted out from under me'

  bool Next(T *&);      // return next item where id & 0xFFFF0000 != 0 (ie items not on free list)

  struct Item {
    T item;
    int id;             // (key << 16 | index) for alloced entries, (0 | nextFreeIndex) for free list entries
  };

  Item *items;
  int maxSize;          // total size
  int maxUsed;          // highest index ever alloced
  int count;            // num alloced items
  int nextKey;          // [1..2^16] (don't let == 0)
  int freeHead;         // index of first free entry
};

```

Handles everything from bullets to monsters to textures to particles, etc. This is the best data structure for video games. I think it came from Bungie (back in the marathon/myth days), I learned about it at Blizzard, and I think it was in a game programming gems back in the day. It's probably all over the games industry at this point.

Q: "Why not use a dynamic array?" A: Dynamic arrays cause crashes. Simple example:

```
foreach(Foo *foo in array)
  if (ShouldSpawnBaby(*foo))
    Foo &baby = array.Alloc();
    foo->numBabies++; // crash!

```

You can imagine cases with more complication (like deep callstacks). This is true for all array like containers. When making games, we have enough understanding of our problem to force sizes and budgets on everything in exchange for performance.

And I can't say it enough: Really, this is the best thing ever. (If you don't agree, post your better solution! Caveat - must address the issues listed at the top of this post: linear memory/iteration, O(1) alloc/free, stable indices, weak references, zero overhead derefs or have an amazing reason why you don't need one of those ;)

# Answer
> 1 votes
There is no right answer to this. It all depends on the implementation of your algorithms. Just go with one you think is best. Don't try to optimize at this early stage.

If you are often deleting objects and recreate them, I suggest you look at how object-pools are implemented.

Edit: Why complicate things with slots and what not. Why not just use a stack and pop the last item off and reuse it? So when you add one, you will do ++, when you pop one you do -- to keep track of your end index.

# Answer
> 1 votes
It depends on your game. The containers are different in how fast the access to a specific element is, how quickly a element is removed and how quickly a element is added.

---

* **std::vector** \- Fast access and removing and adding to the end is fast. Removing from the beginning and the middle is slow.
* **std::list** \- Iterating over the list is not much slower than a vector but accessing a specific point of the list is slow (because iterating is basically the only thing you can do with a list). Adding and Removing items anywhere is fast. Most memory overhead. Non-continous.
* **std::deque** \- Fast access and removing/adding to the end and beginning is fast but slow in the middle.

---

Usually you want to use a list if you want your object list sorted in a different way than chronocially and thus have to insert new objects rather then append, a deque otherwise. A deque has increased flexiblity over a vector but doesn't really have much of a downside.

If you have really a lot entities you should take a look at Space Partitioning.

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


# Question
Title: Smallest increment for a SpriteBatch depth between 0.0 and 1.0?
I experienced some problems with `SpriteBatch` in XNA when I tried to mix two different SpriteSort modes. (Begin with deferred, end, begin with BackToFront wasn't sorting properly.) I've settled on just giving everything I draw with SpriteBatch a depth value.

To that end, what is the smallest increment I can use on the floating point variable that will be used as the depth parameter without running into rounding problems? The valid values for this float are between 0.0 and 1.0. It is a float, not a double, and the language is C#.

UPDATE: My testing has shown that 0.008f is the smallest amount I can change my depth value by and be certain the sorting will work. I'm guessing there is something else at play in BasicEffect or SpriteBatch.

What I am trying to use this for is the rendering of my game's map grid. I want to make heavy use of transparency and overlapping to create a specific visual look for the tiles, the doodads, and the characters.

Essentially, I am using a painter's algorithm to draw the tiles in order from the back row to the front. I have them numbered so I know the ordering is correct. The doodads I am trying to draw on top of the map are not appearing when my depth decrementor is set to a low enough number to draw everything I will need. It only works properly in a range where I can only access about 100 unique depths.

UPDATE about SpriteSortMode problems (as requested):

Thus far in my project I have got by just fine using SpriteSortMode.Deferred for everything. I have all of the standard UI components you would expect, windowing, clipping, etc. working.

Now I am attempting to draw my map grid. Like windowing/clipping this requires things to be done in a specific order to look right. The grid tiles draw in a certain order. To accommodate overlapping, doodads/characters draw on top of a tile before the next tile is drawn.

No matter what I did, my doodads/characters would always be drawn under the tiles. Changing the order of draws had no impact. Even drawing all of the tiles and then drawing the doodads resulted in them showing up underneath the tiles. Especially odd was that my UI elements continued to appear above the problem tiles as I scrolled around the map.

I switched to SpriteSortMode.BackToFront and with a high enough depth difference (~0.01) I see things drawing on the grid as expected, but this depth difference is way too high to support every visible tile of the map. I am searching for a better solution than to write code that will End and Begin a new SpriteBatch every time ~100 pieces are drawn.

# Answer
The answer is:

> 5.9604644e-8

Be very, very careful with it. This is the minimum representable distance between 1 and the next number below it in IEEE 754 single-precision binary floating point, *and nothing else*. I cannot guarantee that SpriteBatch will actually honor it (though it probably will). Also, *any* mathematical operations on two numbers that differ by this much have the possibility to screw you over. (For example: don't halve the depths of two layers that differ by this and expect the two depths to still be different.)

If you use this epsilon religiously, you get 16,777,218 different evenly-spaced layer depths. You probably don't need that many layers. You can use a much, much larger value and have much less chance of breaking anything.

If you want a slightly less magic number, you could write this:

```
1.0f / (float)((1 << 24) + 1)

```
> 1 votes

# Answer
I think your problem is related to the depth-buffer. The depth-buffer goes from the near- to the far clipping plane of your camera (or front-clipping plane and back-clipping plane). If this is a large distance (say `1 .. 1000`) and your objects are placed somewhere at `100 .. 101`, then you're using the depth-buffer very inefficiently.

I'm not entirely sure how the depth-buffer behaves with an orthographic projection, but in case of a perspective projection, it has a much higher accuracy close to the near-plane, where accuracy of far away objects diminishes.

To optimally use the range of your depth-buffer you should set your near- and far-planes as close to your object depth-range as possible. So if your objects are all positioned at z: `100 .. 101` (distance to camera), then setting the near plane to something like `99.9` and the far-plane to `101.1` should help tremendously.
> 0 votes

# Answer
The smallest increment you can do on a float in C# and have a significant value to be different from 0 is float.Epsilon.

From MSDN Single.Epsilon

> Represents the smallest positive Single value that is greater than zero.
>
> The value of the Epsilon property reflects the smallest positive Single value that is significant in numeric operations or comparisons when the value of the Single instance is zero

Single is the equivalent of float in .NET type.
> -2 votes

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


# Question
Title: AndEngine Physics: Shape rotating but not updating physics effects
I was looking at PhysicsExample from AndEngine's Examples. I made the following change that I added a vertical line shape and created a fixture for it. Then I registered a rotation modifier for that shape. It is rotating properly but not updating its physics properties on rotation means when it is rotating and any physics body hits it, it did not give collision effect. Here is my code:

```
final VertexBufferObjectManager vertexBufferObjectManager = this.getVertexBufferObjectManager();
        final Rectangle ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2, vertexBufferObjectManager);
        final Rectangle roof = new Rectangle(0, 0, CAMERA_WIDTH, 2, vertexBufferObjectManager);
        final Rectangle left = new Rectangle(0, 0, 2, CAMERA_HEIGHT, vertexBufferObjectManager);
        final Rectangle right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT, vertexBufferObjectManager);
        final Rectangle center1 = new Rectangle((CAMERA_WIDTH/2) - 2, (CAMERA_HEIGHT/2) - 100, 10, 200, vertexBufferObjectManager);
        final Rectangle center2 = new Rectangle((CAMERA_WIDTH/2) - 100, (CAMERA_HEIGHT/2) - 2, 200, 10, vertexBufferObjectManager);

        center1.registerEntityModifier(new LoopEntityModifier(new RotationModifier(2, 0, 360)));

        final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f);
        PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef);
        PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef);
        PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef);
        PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef);
        PhysicsFactory.createBoxBody(this.mPhysicsWorld, center1, BodyType.StaticBody, wallFixtureDef);
        PhysicsFactory.createBoxBody(this.mPhysicsWorld, center2, BodyType.StaticBody, wallFixtureDef);

```

Although the body give collision effect when it reaches the shapes initial position. I am new to AndEngine. Where I a wrong...???

# Answer
> 3 votes
You are only rotating the Shape, not the physics body. The Shapes follow the movement of the physics bodies of Box2D, not the other way round.

---
Tags: android, box2d, andengine, physics-engine
---


# Question
Title: Where and how to promote an HTML5 game engine?
I've recently completed an engine, called Irenic.

Now, I was wondering, how could one promote it? The process surely is different than promoting a game, because a game can be played by almost anyone, and a game engine can be used only by developers. Aside from obvious things such as posting on Gamedev.net, are there some lists or wikis I could post it to? Other ways?

I'm not really interested in people using my engine, but rather giving some feedback and so on. Just getting it out there would be cool.

# Answer
> 9 votes
What I would recommend is:

* There are some lists to add it to, like this one (make sure you also update the feature matrix) or this http://html5gameengines.com/.
* Try following the same search patterns someone would follow when they're looking for a HTML5 engine. Do a Google search for HTML5 engine, see what shows up. If there are lists, see if you can add your engine, or ask the site creator to add it for you.
* You can write a press release and send it to sites like IndieGames.com who have a section for indie tools.
* Write a post about it on gamedev.net like you suggested. Just get the word out there, linking your game engine to key words related to HTML5 game engines. Work the Google-foo.
* Post on forums for people asking about what engine to use.

# Answer
> 1 votes
If you have a game engine it really needs a show case demo. A full game would be the best but just a technology demo does make a difference. As a developer I don't have interest to build my own proof of concept around unknown engine unless there is some promise behind it.

So, promote your 'Den of Anomy' game and/or provide some examples of the basic game functionalities implemented using the engine.

---
Tags: marketing
---


# Question
Title: How do i choose what technology to use for a 2D game like Pokemon?
I apologize in advance for the wall of text about to come. I've had an idea for a game for a while now, and am stuck at step 1 of game development: Choosing a language/engine. I've read a whole bunch of articles, comments, and posts, but everything recommends a different combination, and they all just give me more questions with less answers. I'm hoping someone here has some experience with what I'm trying to do, and can let me know what's what.

So, for the sake of this post, let's assume I'm writing something akin to one of the old Gameboy Colour Pokemon games, but with nicer graphics. Like Pokemon, with "Zelda: A Link to the Past" graphics. I've looked into the following options in terms of the technology:

* C++ using SFML
* Java using LWGl
* Java using LibGDX
* Python using PyGame

Each of the above has pros and cons, but I don't know **which** pros and cons apply to **me**. I am comfortable with any language and library, I already know a lot, and am more than happy to learn more. My three questions that are holding me back from making a decision are:

* How do I choose a technology now without knowing that it can "handle the load" without chugging along? What if I choose Pygame, and 60% of the way through development I can't get the FPS above 15?
* How do I know which engines are better suited to "2D Zelda/Pokemon" gameplay? I've been recommended 1000 different engines and libraries, but most of them are for 3D effects or insane physic (which I likely won't need).
* How do I handle cross-platform stuff? I want to distribute on Windows/Mac, and Linux as well. Java is easier for this, but what if it's not performant enough (compared to C++)?

So, does anyone have experience with anything like this? Has anyone been where I am before? I want to get started, and dip my feet into the proverbial water, but I'm too held back by indecision on technology to get my toes wet.

If anyone can recommend an engine/language/toolset for me, and maybe point me towards some tutorials or guides, I would be greatly appreciative.

# Answer
My advice is to use the higher level language first. It will ensure that you will spend the most of the time around game-related topics instead of lower lever stuff (this is a pro!).

If it gives you good performance you are done; if not you can profile what slows things down (and is easier to profile a software written in an high level language).

Once you found your bottlenecks you can:

1. rethink how the things work (design issue) and then rewrite the modules better (+1 knowledge)
2. rewrite a module in a lower level language (interpeter issue), the module is a small part of software with a limited and well defined boundary and responsibility (+2 knowledge, +3 focusing)
3. seek a better framework (framework issue), since the frameworks runs the most of the time in native code, probably the one you choosed was not so good. You have to rewrite some part of your application to deal with the fact that the framework changed: less changes =\> good designer (+4 knowledge, +2 learning speed)
4. vaporize everything without leaving a trace and restart the project using a lower level programming language. You learnt so much from this failure that ultimately it's worth the efforts.

In my experience the chances are that you will touch the step 1. once or twice for high level stuff (no more if you are good enough) and the step 2. for fine-grained routines (even if not necessarily)
> 4 votes

# Answer
What about http://en.wikibooks.org/wiki/Super\_NES\_Programming ?

Seriously now, I followed a path similar to the one you are about to follow. PyGame is great for learning, there is absolutely no doubt about it, it's "Code The Correct Way" philosophy is extremely valuable when getting into game development.

I started a new SFML2.0 project last month and it would be really tiring to list all the things that having worked with PyGame before simplified the developing process for me.

But of course, it depends on your capabilities. I tried C++ game development before PyGame and, though even more unexperienced and young, I couldn't even get started. But it would be pointless to try to crash head first into C++ and game development at the same time without a pretty good reason, each one already has a ton of concepts, and even though Python also does, they are easier to learn (not because of less complexity but because Python's user-friendly design).

And I really plan to program a SNES game some time, but first I need to efficiently handle sprites inside arrays :D
> 2 votes

# Answer
Choose any you feel most comfortable with. From my own experience performance will be the last thing you will be troubled with.
> 1 votes

# Answer
Java vs C++ for cross-platform 2D game: I would recommend **Java unless you're expert C++ programmer**, because it's much easier to write code in Java - no pointers, very huge standard library compared to c++ and no cross-compiling required.

Java can be slower than C++, but that applies mainly at advanced programmers, because you have to handle more stuff on your own in C++ and if you don't know to program very well you can have much worse performance with C++. Main disadvantage that applies for Java is that it's memory hungry (cca 100MB is consumed by JVM), but that's not problem now, most of users have at least 2 GB ram.

---

Which engine to choose? I wouldn't recommend any, but don't choose anything that isn't accelerated by OpenGL. It very depends on you and game you are going to create. Just try all engines you find and choose one you liked at most. For 2D you don't even need any engine, because it's very easy to write it by yourself.

I didn't heard about libGDX before, but I think it will suits for your app.
> 1 votes

# Answer
Performance will likely not be an issue for you if you only plan on making a simple 2D RPG. If you do end up having performance issues, it's MUCH more likely that you've made a poor decision in your algorithm. The biggest effects on performance isn't the slight differences between languages in small-scale programs. Often, it's not the language, or the library, or even the hardware! Many times, if you want to optimize your program, you should first check to make sure that your algorithms aren't wasteful/illogical.

Basically, I think that you would be able to make the type of game that you want to make in any of those language/library setups. It really depends what you feel comfortable with!

The mantra that I've always been told is, 'don't worry about optimization until you have WORKING code'. Pick a language, pick a library, start learning and plugging away, get your game working on a basic level and see how it runs. If it isn't running as fast as you'd like, then check you code and see if you can rewrite your algorithm in a smarter, more efficient way!

From the options that you suggested, I personally think that Java is the most 'middle of the road' and it kind of lies between C++ and Python. But I think you can do what you want to do in any of those languages. :D

Good luck!
> 1 votes

---
Tags: c++, java, 2d, python
---


# Question
Title: Learning math from the basic to become a game programmer
Hi i want to become a game developer. Im currently doing some web programming. I want to learn game programming. Im not good in math thats why i decided to learn from basic math to be sure i will not missed some important concepts. Do you have some advice if my way of learning is ok. thanks.

# Answer
I have recommended earlier editions of the following book, and I imagine the current edition is equally good:

http://www.amazon.com/Mathematics-Programming-Computer-Graphics-Edition/dp/1435458869

After digging into that, my suggestion is to just practice: make some games. When you run into specific problems, find the answer to them.

You can spend an entire lifetime learning the "foundations" of a craft without ever learning how to actually do perform that craft. You'll only actually learn it by doing it.
> 3 votes

# Answer
Have you checked what-math-should-all-game-programmers-know?

If you want to get into 3D then you will need to understand vector operations such as dot-product and cross-product. You will also need to understand matrix basis representation and representations such as the world-matrix. The easiest way is to follow a tutorial for some "My first 3D game" and try to understand the math as you go along.
> 3 votes

# Answer
Try starting with basic addition(+) and subtraction(-) followed by multiplication(\*) and then division(/) and fractions. If you can get to the point of working with three digits(804/268, for example) then that would be best before you continue.

After that you should start with algebra (A+B=C). When programming games (or programming in general) you will be using a lot of algebra.

I would say that only after this point should you start to play with actual code. Math.com is a great FREE place to learn all you need. Good luck :)
> 1 votes

---
Tags: mathematics
---


# Question
Title: Advice creating build process for medium sized game project
I've been looking through the SCons build script for Doom3 and researching different approaches to build processes used by professional game developers/studios (C/C++) and I've come across a few questions:

1. When creating a build script (scons/make file etc.) is it used *every* build when coding within an IDE like say Visual Studio? In other words do you tend to just use the tools in Visual Studio (Project files etc.) when you want to test a small code change? Or do you step outside VS and run the scripts to get the project to a point that it can be run?
2. An extension of question 1, if you use VS entirely for these kinds of builds, how far do you take it? i.e. do you have it copy the game into a folder with all the assets or run any kind of install scripts?
3. If your feeling generous could anybody give me a quick overview of the kind of things you're including in your build steps? Asset creation/install scripts/folder structure creation etc.

Many thanks all.

# Answer
I'll try to answer to the best of my knowledge, even if I'm far from a build process expert.

1. Typically, when changing code:

* Most of the time, just running the compiler + linker is enough
    * When adding/removing/renaming source files, it's necessary to close the IDE and run CMake, Premake or similar to recreate your projects/makefile/etc. (if such a tool is in use)
    * And that's only when doing a code change that isn't compatible with current data that the data needs to be binarized again
2. If you're talking about a whole build process, including binarizing data, creating installation script, etc., then no that's usually not something that's done from an IDE. It's usually managed by some continuous integration software, or just a bunch of custom scripts, run automatically overnight for big projects.
3. I won't go into folder structure, as there is no standard for that, just follow your instinct on what you feel is best. Just make sure you have a clear distinction between source code/assets and generated stuff, this helps keeping version control clean. What a build process does usually is as follows:

* Generate the projects for all platforms & configurations
    * Build the code for each project
    * Binarize all data
    * Package: create disc images, installation scripts...
    * Run automated tests
    * In case of failure, report errors
    * In case of success, archive the build somewhere
> 5 votes

# Answer
There could be multiple things being discussed here. Generally you have one and precisely one build method, where this is how you produce the executable. If you had more than one, then they risk getting out of sync, and it's another variable you have to consider when troubleshooting. You don't want your IDE's Build command using different settings to the one that a proper build does (except for Debug/Release distinctions, etc.)

But often what we call a build script includes building assets, deploying to test servers, etc etc, and you obviously wouldn't do that on your own machine every time.

With scons, makefiles, and similar, you can set up different targets so that one tool can perform both roles. You'd probably set up Visual Studio to run the basic executable-only build, and if you needed a full build exe/process assets/package/test/deploy system, you might do that outside the IDE.

Generally I wouldn't go too far with putting the whole process in Visual Studio - it's likely to be something that non-programmers are going to want to be able to do, providing there is an up-to-date executable available. It's also commonly automated, for example to have a system that automatically continually performs full builds to see if anything has broken.
> 3 votes

---
Tags: c++, c, build-process
---


title: Choosing the right game engine

text:
# Question
Title: Choosing the right game engine
I'm trying to create a game in java inspired by a Gameboy Color Zelda game. I'm exprienced in java but not in game programming. I've been doing a lot of research on game engines, and I'm currently considering JGame, GTGE, and Slick. Are these engines (or any that I have not seen) suited to a 2D game that entails a large environment and saved files? What engines would be suitable for this purpose? On a side note, I'd also like to eventually make this game playable on Adroid, if that factors into which engine to choose.

# Answer
> 4 votes
There is crossplatform game engine - LibGDX.

I haven't tried it, but it seems to be engine you're looking for.

---
Tags: java, 2d, android
---


title: Box2d Collision problem

text:
# Question
Title: Box2d Collision problem
I'm not good with words so here's a picture to describe my problem:

In my game there is this big ball which the user can move on x-axis only. Now, if the ball is falling like the red one, it's blast away. **But**, with the angle/hit position of the green one it's just kinda sliding on the big ball and falling.

I'm using Box2d above AndEngine on an Android platform.

What is the reason for my green ball problem?

# Answer
> 2 votes
Good image i can understand your problem much better from it. To solve this problem i would use some extra conditional statements(if you dont have them already). anyway here is how i would go about trying ti implement your project:

1. First the balls will need velocity(i assume you already have this).
2. The angle of incidence with the circle will need to be calculated when the collision happens.

3 you will need a conditional statement to tell the ball whether to trail along the outline(sorta like viscousity) or to bounce straight off. This condition is based on the incoming velocity and angle of incidence. If the ball is travelling slowly for example you will tell it to continue its path around the circle. However if the velocity is high enough and angle of incidence is also high you will resolve the new velocity based on incoming velocity and angle of incidence * some factor (if the circle is hard its(the factor) \*1, soft * less than 1, bouncy * greater than 1).\`

# Answer
> 0 votes
It looks like your problem is with **Restitution**. Look at section 6.2 in the Manual. I'm not sure if AndEngine exposes this value but in libgdx, setting this property will give you the behavior you're looking for.

# Answer
> -1 votes
You could always register a custom ContactListener with your World. Create a class and implement the ContactListener interface, which containts 4 methods:

```
public void beginContact(Contact contact);
public void endContact(Contact contact);
public void preSolve(Contact contact, Manifold oldManifold);
public void postSolve(Contact contact, ContactImpulse impulse);

```

Then you can get a WorldManifold from the Contact that will tell you the normal of the two objects colliding. Filter out the collisions so that you know it's one ball colliding with another ball (I find the `instanceof` keyword to be useful for this) and then apply some force in the opposite direction of the normal.

---
Tags: java, android, box2d, mobile, andengine
---


# Question
Title: Android Cocos2DX using C++ in Eclipse Helios Windows XP
I have used Eclipse Helios 3.6.1 for Java development. I wanted to start C++ development in the same IDE so I installed **Autotools Support For CDT, C/C++ Development Tools, C/C++ Library API Documentation Hover Help plugins**.
I have included **#include "cocos2d.h"** in my **HelloWorldScene.h** file now when writing the below statement
`cocos2d::CCSprite * ccSprite;`
I am not getting auto completion bar(template proposals) on writing like coco and pressing **Ctrl + Space** from my keyboard. What can be the problem?
This might help you solve my problem. Please check here. This is what I got after clicking Right Click Project -\> Index -\> Search for Unresolved Index. But I have added all includes check here. I think this is causing problem in Content Assist. What should I do in this case? Inclusion seems proper.

# Answer
> 1 votes
Have a look at this question The second link under beginner has an indepth explanation of how to set up xcode for iphone and eclipse for android

---
Tags: cocos2d-x, eclipse
---


# Question
Title: AndEngine: Density, Elasticity, Friction, Gravity concepts
I am new to AndEngine. I have seen some physics examples from AndEngine Example package. I want to know the role of density, elasticity, friction and gravity while implementing physics. How they effect a physical object in andengine? I know its very basic example but I want to start andengine from very basics. Can anybody make these concepts clear to me?

# Answer
> 4 votes
AndEngine uses Box2D. You can find more information simply by seeing the manual, which includes explanations for the concepts you're asking, here. Specifically, 6.2 :)

For examples, if you feel confortable with javascript, I would suggest you to go here, a website with a lot of working examples of a Javascript port of Box2D (I believe that the names of the classes are the same).

---
Tags: physics, andengine
---


# Question
Title: network programming: simultaneous IO over sockets?
In my curses based game, I decided to add multiplayer functionality over net, in addition to one-keyboard mulitiplayer game. I use switch loop and in case it's 1st user's buttons, user 1 is acting appropriately and second otherwise, without blocking each other's movements i.e not waiting for opponents move. Now I read socket tutorials, and use server looking like this:

wait for 1st user to connect wait for 2nd user to connect

loop: read from 1st write to 2nd read from 2nd write to 1st

Now problem is obvious, players would block each others movements, how this network multiplayer problems solved in games design?

# Answer
Basically you wouldn't write a server like that. Those tutorials are showing you the basics of 2 reading and writing and assume 2 trusted processes that are guaranteed to cooperate.

Instead of waiting for a message from one client before the code continues to send a message out to another client, the server waits for messages from all clients simultaneously. When one arrives, it will check its business logic to see if the message came from the client it expected, and if so, it will process it accordingly. So instead of a loop which reads from each side in turn, you read from whoever sent something first, respond accordingly, and repeat.

To wait for multiple clients you usually use some variation on the `select()` function to tell you which client has data ready for you to read it. Or better still, you use a library that wraps that (or a similar alternative) in some way.

There's some explanation of the `select()` function here: http://beej.us/guide/bgnet/output/html/multipage/advanced.html

The code there is in C, but you'd use something very similar in most languages. If you use a 3rd party library, usually they handle this part for you, and call a callback that you provide when the message comes in.
> 4 votes

---
Tags: networking, multiplayer, socket
---