# Question
Title: What features do basic particle engines have?
I created a basic particle system for SDL in C++. It has some basic stuff like an emitter, as well as a simple particle class. It can load a image, or create a dot of a color. And that's it. What other features do most simple particle engines have? Keep in mind this is a 2D particle engine.

# Answer
This is a very broad question, but generally particle system features can be broken down into a few categories. Here are some general ideas for the sorts of things you might want to have.

**Emission features** define how, when, and where particles are emitted.

* Continuously generate particles at a fixed rate, or generate a cluster all at once when triggered by some in-game event.
* Place newly-emitted particles at a point, or randomly within a region, such as a box or circle. The point or region could be moving, e.g. attached to an object or character.
* Emit particles at a rate proportional to the velocity of a moving object, which can be useful for smoke trails and suchlike.
* Give the particles a random initial speed and direction, within certain ranges. For example, an explosion would send particles in all directions while a cannon would send them in the direction the cannon is pointing.
* Optionally have particles inherit velocity from their emitter, when the emitter is itself moving.

**Motion features** control how particles move after they're emitted.

* Gravity or buoyancy makes particles sink or rise.
* Collision detection can be used to make particles respect walls, either by flowing along them or bouncing off.
* Air drag causes fast-moving particles to slow down.
* Particles also might move along a spline defined by the designer, or be attracted to a particular point or region (possibly attached to an object or character), etc.

**Rendering features** control how particles look.

* You almost certainly want to have the particles change size, color, and alpha as they age. Animation curves can be defined to control these.
* For a 2D game, the Z-order of particles relative to other game objects should also be controllable.
* For sprite particles, you might like to have the sprite rotate. It could spin at a random speed, or rotate to face its direction of motion, or the direction its emitter was moving when it was emitted.
* Also for sprite particles, you might want to have it run through a sequence of animation frames.

These are just a bunch of general ideas. For your specific game you might only need a couple of these, or you might need other ideas that aren't on this list.
> 19 votes

# Answer
Watch this video for some ideas that you can add to your system, in particular *modifiers*, which can be used to interpolate particle properties over time, such as color or opacity, or to apply complex gravitational forces to the system. These are often enough to create some really cool effects, when combined with a basic particle emitter.

Afterwards, you might want to check the documentation of some existing particle engine to see what else they provide. The first one that comes to my mind is the Mercury Particle Engine, which also seems to be built around the concept of particle emitters and modifiers. Give it a test drive and it should be enough to answer your question.
> 3 votes

---
Tags: c++, 2d, sdl, particles
---


title: Should my game states be JPanels?

text:
# Question
Title: Should my game states be JPanels?
I'm thinking about making a `StateManager` for my game. I want to know how to design it; that is, how to use a stack to push and pop states onto, and draw them to the screen.

For example, should each `State` be a `JPanel`? I want to make a `Menu`, preferably using `JButtons` if possible. I don't want to add them directly to the main panel because I don't want to have to constantly add and remove those buttons. Also, not all my states are going to be drawable, since I might have a state that contains a MouseListener to detect clicks.

Right now, I have an empty `State` class. My `Menu` class extends from that. My state stack is of the type State. Another design question: if in my `Menu` I click the "Play" button, should I just say something like `StateManager.push(new PlayState())` from the `Menu` class?

# Answer
> For example, should each `State` be a `JPanel`?

It's generally better to favor aggregation over inheritance. So your `State` class shouldn't *be* a `JPanel` (= *inherit* from it), but should probably *contain* a `JPanel` member for rendering its content.

That's because your states don't do rendering only, but also manage many other things. Better yet, if for some reason you need states without a `JPanel` this might mean less code changes.

> If in my `Menu` I click the "Play" button, should I just say something like `StateManager.push(new PlayState())` from the `Menu` class?

Sure! Just make sure your `StateManager` releases the reference to the `Menu` state when it's done switching to `PlayState`. Otherwise you'll get memory leaks.
> 3 votes

---
Tags: java
---


title: Writing a shader once without using CG?

text:
# Question
Title: Writing a shader once without using CG?
Is there a tool that can convert a fragment shader from hlsl to glsl or glsl to hlsl? I do not want to use cg since it is not able to work on mobile platforms.

Is there a tool that can make it so I only write a shader once?

Thanks

# Answer
> 2 votes
Shiny is a new library that aims to make material management and portable shader writing easy. This is achieved mostly with a preprocessor meta language, that can output any of CG, HLSL or GLSL. It is currently geared towards usage with Ogre graphics engine, but that part is abstracted into a separate component, so it shouldn't be hard to plug in any other engine. The library has been / is being integrated into OpenMV and Stunt Rally (*disclaimer: I'm a member of the latter*).

There is a lengthy introduction here.

# Answer
> 1 votes
I can't vouch for either one, but there is a utility available here for going from HLSL to GLSL: https://github.com/aras-p/hlsl2glslfork

and here for going the other direction: http://code.google.com/p/angleproject/

The first one is explained more here: http://aras-p.info/blog/2010/05/21/compiling-hlsl-into-glsl-in-2010/

# Answer
> 0 votes
There's the tool MojoShader which accomplishes what you want: http://icculus.org/mojoshader/

---
Tags: shaders, glsl, hlsl
---


# Question
Title: Rendering a Sprite with an Effect.... how?
gettings tuck doing some 3d Rendering and I think you guys may have a lot more knowledge in it. I am tasked with basically rendering a texture onto a screen, preparing the way to apply graphical effects there (including some color space conversions later that shall move from the CPU to the graphics card.

My idea to do that is pushing the data into a texture, then render it as a sprite onto a surface or texture that then gets presented (it is going to be transformed by code from other people into some show of videos that are part of a larger scene).

Sadly, for technical reasons this means C#, DirectX9 and I decided to use SharpDx as DiretX wrapper.

I am slowly making my way into the whole thing. For the start, we have an A8R8G8B8 texture to render to, and a source in the same format (which will change later, including some foramats DirectX does not support - thus the idea to use PixelShader to transform for example color spaces).

Where I am stuck is:

* I can not get an Effect to do ANYTHING. HI ahve the idea my setup is somewhere wrong. Sadly finding out how to apply an effect to a sprite is - very hard, given that most stuff on the internet deals with more recent versions of Direct x.

My code:

There is a SIMPLE effect that should just chane the colors of the pixel. This is a test, but the pixels get rendered normal, so something is wrong. The Effect code is:

```
float4x4 World;
float4x4 View;
float4x4 Projection;

float4 AmbientColor = float4(1, 1, 1, 1);
float AmbientIntensity = 0.1;

struct VertexShaderInput
{
    float4 Position : POSITION0;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    float4 worldPosition = mul(input.Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);

    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float4 output;
    //output = AmbientColor * AmbientIntensity;
    output = float4(0,0,0,0);
    return output;
}

technique Render
{
    pass Pass1
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

The way I try to render it is:

I get the Effect like this:

```
Dx9.Effect effect = Dx9.Effect.FromFile(m_Device, "SpriteNopEffect.fx", Dx9.ShaderFlags.Debug);

```

I select the Technique:

```
effect.Technique = "Render";

```

That works -. if I change the name then it blows, so the effect file is loaded and the effect found.

The render code is:

```
        m_Device.BeginScene();
        Dx9.Sprite sprite = new Dx9.Sprite(m_Device);

        effect.Technique = "Render";
        int passcount = effect.Begin();
        for (int i = 0; i < passcount; i++)
        {
            effect.BeginPass(i);
            sprite.Begin();
            sprite.Draw(
                texture,
                new SharpDX.Rectangle(0, 0, m_Width, m_Height),
                new Dx.Vector3(0, 0, 0),
                new Dx.Vector3(0, 0, 0),
                new SharpDX.Color4(0xffffffff)
            );
            sprite.End();
            effect.EndPass();
        }
        effect.End();

        m_Device.EndScene();

```

And here the problem is - whether I have the effect in or not, the output is the same, so EITHER my effect is bullocks OR - the effect is simply not applied.

Any help appreciated.

# Answer
I think `Sprite.Begin` will set it's own shader for drawing sprites and overwrite yours. So change the order.

```
sprite.Begin();
effect.BeginPass(i);

```

note: This is how it works with Xna, and i don't think your shader is ready for what sprite.Draw will do
> 4 votes

---
Tags: sprites, directx9, sharpdx, effect
---


title: Parent-Child position mathematics

text:
# Question
Title: Parent-Child position mathematics
What is the math theory when a child object moves with the parent transform?

I am doing an angle indicator which shows a field of view, which works fantastic when the angle is static. But I cannot get the field of view indicators to play nice with the angle changing. Everytime I change the angle, the indicators are reset to default positions and then the direction indicator and FoV indicators are out of sync.

There is of course a ghetto way of resetting the whole thing when changing the angle, but I'd prefer not to do it that way.

The red circles are the points which are used to draw the FoV lines and they are childed to the white sphere. If the angle is not modified after start they follow the white sphere nicely and show the FoV correctly.

Here is how it looks after trying the dynamic angle changing. The FoV lines should be pointing to the right and the white sphere should be in the middle.

Currently I am changing the red circles' position based on the angle given(transform is the green square in the middle.):

```
leftAngle.transform.position = transform.position + new Vector3(Mathf.Cos(firstLineRendererAngle * Mathf.Deg2Rad), 0, Mathf.Sin(firstLineRendererAngle * Mathf.Deg2Rad)) * 10;
rightAngle.transform.position = transform.position + new Vector3(Mathf.Cos(secondLineRendererAngle * Mathf.Deg2Rad), 0, Mathf.Sin(secondLineRendererAngle * Mathf.Deg2Rad)) * 10;

```

How do I add the position of the FoV direction sphere to emulate parent-child relationship with the objects?

# Answer
Solved this by checking the angle of the EyeDirection(white sphere) and then substracting that amount from the indicator angles.
> 0 votes

# Answer
I believe the theory you're looking for is Affine Transform

> ...is a transformation which preserves straight lines (i.e., all points lying on a line initially still lie on a line after transformation) and ratios of distances between points lying on a straight line (e.g., the midpoint of a line segment remains the midpoint after transformation).

And an affine transformation is equivalent to a linear transformation followed by a translation, which I believe is the ghetto method you were talking about?

Anyway, you can find a Unity specific answer about affine transforms here.
> 0 votes

# Answer
You could use a transform heirarchy, making the transforms of the 2 red balls children of the transform of the white ball.
> 0 votes

---
Tags: unity, vector
---


title: OpenGL ES and Screen Coordinates

text:
# Question
Title: OpenGL ES and Screen Coordinates
Is there anyway I can make OpenGL ES 2.0 to accept coordinates (for `Vextex` for example) in `int` meaning the pixels instead of the default `float` system? Also how can I set the point `(0,0)` to be at the top left corner of screen instead of the default one at the exact middle of the screen (to make using the pixel coordinates system easier)?

# Answer
If you are making a 2D style game, you can use, for example a 320x480 screen coordinates in your code, and then, in your vertex shader, you need to transform them into OpenGL ES coordinates.

I recommend you to use a MVP matrix, for all your vertex operations, but for a naive implementation of an orthographic 2D projection, you can do it manually as follows:

```
// Minimalist vertex shader
#version 100

attribute vec3 position;

void main(void)
{
  gl_Position = vec4(position.x * 2.0 / 320.0 - 1.0,
                     position.y * -2.0 / 480.0 + 1.0,
                     position.z,
                     1.0);
}

```

This vertex shader puts the screen coordinates origin at the top-left corner. And transform your coordinates from 320 x 480. From here, replace the 320 and 480 values as you need.

The orthographic projection matrix is shown here: https://gamedev.stackexchange.com/a/4312/3020
> 3 votes

# Answer
I don't think you can use int's when you're sending your data through the shaders. And if so, you shouldn't. The GPU is designed to fast process floats in parallel so try to stick with that if possible.

For the second question you should read up a little on how the projection of a 3d scene works when it gets projected onto the "view" or screen as mentioned here: https://stackoverflow.com/a/6150298/341358
> 1 votes

# Answer
I'm assuming you are trying to draw in a 2D system. Your best bet is to use an orthographic projection by calling

```
glOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble nearVal, GLdouble farVal)

```

or the equivalent function for the matrix creation functions/helpers you are using. This way, you can specify your coordinates relative to the screen, and if your screen resolution is 800x600 you can use

```
glOrtho(0, 800, 600, 0, 0, 1)

```

to get a transformation matrix that will let you specify your coordinates in pixel values and with the origin in the top left corner.
> 1 votes

---
Tags: opengl-es, coordinates, opengl-es2
---


title: Fair sharing income with designer

text:
# Question
Title: Fair sharing income with designer
I am developing my android game, 2D Sidescroll arcade game, its almost finished, I found artist who wants to cooperate with me, creating graphics for my game, but we have to discuss how much % he will receive if there will be any income from our game.

How do you game developers handle this? What is fair share for an artist? Here is little description on my and his work, to estimate work value:

**Done by me:**

* game idea, story
* game code (6 months of development) all game features, everything generally
* visual level editor
* levels created by me (more than 120)
* android license bought be me (I know its cheap but still it is value)
* sound purchased by me

**Done by artist:**

* game graphics generally, ground tileset, game characters, 5 tiled monsters (animation), around 30 different graphics for different game objects (like environment elements, obstacles etc)

I would be grateful for some informations, thank you!

# Answer
> 3 votes
There is two maybe three ways to approach this, But what you have to remember is you have a found a artist who wishes to work with you and you will want to keep hold of that contact and not cause any "bad blood" to occur. Some ways to approach this:

1. One Time Payment - You can offer this if you are willing to basically buy the rights to the images off of them this has the advantage to the artist as they make money regardless of if you game sells and you also as if it sells you get all the profit, Only Cons i can see is refinements to the graphics won't be as easy nor additional content as again it would be one time payment.
2. Percent Split - This method is wrought with issues and can cause the "bad blood" situation. An artist can and do put as much time into the images as you do into the code and without each other they would be no game (at least not a sellable one) so you have to decide if that worth the arugments. Why not ask them what they believe there work is worth? then haggle till you are both happy with it?
3. Partnership - Split everything down the middle, costs and profits. This one a big decision but an artist could be worth it.

Hope this helps

# Answer
> 0 votes
If you are running the project as hobbyists I believe a fair share is to just weight your share of the profits based on total workload. If you worked 300 hrs and the artist 100 hrs then share the profits 75-25. In case there are people on the team who contribute with unique skills like artists or musicians that are really hard to find then maybe count their worked hours as double os something.

---
Tags: android, publishing
---


title: The Physics behind 2D Platformer Games?

text:
# Question
Title: The Physics behind 2D Platformer Games?
Is there any good book or tutorial that explains the physics behind creating a 2D Platformer game? Such as tile rendering, tile map reading, collision detection, camera movement etc.?

# Answer
> 12 votes
I think I stumbled upon this link here on gamedev and I really found it enlighting.

http://higherorderfun.com/blog/2012/05/20/the-guide-to-implementing-2d-platformers/

It explains some basic methods of implementing tile based levels, but there are also some important parts about how certain mechanics work in 2d platformers. I think you should look into slopes, as they can solve many problems you come across in platformers.

Good to know is, that most platformers don't even bother with implementing proper physics, but implement certain rules, that mimic some physical behavior (like gravity), but allow certain behaviors that wouldn't be allowed with proper physics (air control for example).

---
Tags: 2d, game-design, physics, platformer
---


# Question
Title: Structuring various game states and unique levels
I have a game design 'structure' question that I'd like to throw out there. This question is about various ways of designing game 'states', and specifically a system of 'levels'. Specifically, **what is the best way to design a game that has multiple game states, as well as multiple 'levels' or 'stages' with varying degrees of similarity to each other?**

---

**For example:**

**1)** Image you're making a 2D platformer with various game states (i.e.: *splash screen, animation 'cutscene' sequence, main menu, playstate, pause menu*, etc...).

**2)** Also consider that the game might make use of multiple 'instances' of various states. (For example, maybe you have a "*MenuState*" class, which is used for both the games '*main start menu*' as well as the game's '*game over menu*'...)

**3.)** Now, consider that the game will have multiple levels, which all play more or less the same way, and they all reflect the '*playstate*' game state. (so, \[*level 2*\] and \[*level 6*\] are fundamentally the same in game play, but they probably contain very different details, sprites, music, enemies, bosses, etc..)

**4.)** Also, hypothetically speaking, what about if you had a second type of '*playstate*' that acted in a fundamentally different way? (for example, maybe you have an overworld, or a *fundamentally different type of level*.)

---

This is essentially the crux of my question... I'll try to demonstrate what I'm talking about using generic pseudo-code:

So, in this game, we'd have a main(), some kind of StateManager class, and various classes for the different states:

```
int main()
{
init();
StateManager->handleEvents();
StateManager->handleLogic();
StateManager->checkGameState();
StateManager->handleRendering();
cleanup();
}

```

The main function would also be some sort of loop with FPS regulation and all that, but for the sake of clarity I'm just going to leave it like that. So main() uses the StateManager to do most of the work, and the state manager would then take care of switching states and it would pass it's event/logic/rendering responsibilities to whatever is the 'current state'. And because the state manager itself is something that I've been having difficulty working out the specifics, I'll leave that for another discussion entirely...

**The main issue that I'm looking for help with is the class hierarchy of the various states, as well as when to use inheritance vs when to simply create an instance of an existing state...**

Here's my current (limited) understanding of how I've been thinking it should be structured. Honestly, I need help with this part specifically, so I expect it to be slightly wrong:

* **GameState class** (top of the state hierarchy, contains virtual event/logic/render functions)
* **SplashScreen, AnimSequence, Menu, PlayState classes** (all of the classes ARE gamestates, and as such they should extend the GameState class)

That's all good and fine, but, here comes my main source of 'fuzziness'...

**multiple very similar states:**

* In the situation where our game has multiple splash screens, animated sequences, menus, or playstates, how do we structure that relationship? My first instinct is to create instance objects of those various classes. For example, if we want to make multiple different menus that all function in similar ways, what is the proper way of doing that? Should we create new objects of the Menu class called mainMenu, saveMenu, deathMenu, etc.? Or is the correct way to do this via inheritance? Creating new, MainMenu, SaveMenu, and DeathMenu classes that extend the Menu class???

This has really been a source of confusion for me with Object Oriented programming. *In this kind of situation, would I be smart to create a subclass or simply instance the existing class?*

**a system of levels and their interaction with the PlayState class:**

* Another point of confusion for me is the use of multiple 'levels' or 'stages' that play the same way, but have different layout, enemies, bosses, sprites, music, etc... Lets say we want to create a short game with 10 unique 2d platforming levels. Now, the thing that's giving me difficulty is how these 10 levels interact with the PlayState class. Would these 10 levels be instance objects of the PlayState class? Or would it be more beneficial to have a Level class, with 10 level objects, which are used by the PlayState class? Or maybe I'm thinking about this completely the wrong way and Levels are a subclass of PlayState, and each one is it's own unique playstate?

**Overworlds and MiniGames as a Secondary PlayState:**

* Finally is the question of an **secondary playstate**... Regardless of whether it's an overworld, a different game mode, a minecart level, a minigame, or whatever. Would this second playstate just be a complete seperate subclass of the GameState class? For example, if we have our main PlayState (platformer game state) and we also want to have a top-down overworld, and a completely unrelated puzzle minigame, would these simply be other descendants of the GameState class, in the same 'tier' of the class hierarchy?

---

Thanks to anyone who has gone through the trouble of reading this compound question regarding various states, levels, and game class hierarchies. I know that the quality of opinions and information on this site are often very high, and I hope that this discussion will be as useful to other people with similar questions as it will be for me!

---

# Answer
Generally, I'd want one class per, well, class of screen. So that'd be one for splash screens/animations (probably the base class for all screens, with support for background images and screen transitions), one for menus, and one for playstate. Each then can be parameterised by its contents - the difference between a main menu and an options menu, for example, are just the various different menu items it contains and the screen's transitions to other screens.

Generally, I'd make MenuScreens take a Menu item of some sort as an input, PlayStateScreens take a Level, and so on.

If you have a secondary gameplay, it may make sense to reuse the PlayStateScreen: the job of this screen is to oversee updates and draw items, so if it's still acting on game entities and drawing sprites in the same way as the main game, then it makes sense to reuse the same screen. If it's something like, say, BioShock's hacking - 2D instead of the main game's 3D, and interaction via pointer rather than mouse for looking - that's a good reason to use a different set of logics. A map view could go either way - if it's still manouvering round a tilemap, and you still want to draw entities with sprites and have scrolling support and so on - then you could use the same PlayState class, and just have entities which use different logic.
> 2 votes

---
Tags: game-design, state, levels, architecture, oop
---


# Question
Title: How to accept microtransactions with a desktop application?
I want to implement microtransactions into a desktop application I'm working on, but the microtransaction services I know of are all targeted primarilly towards Flash or smartphones. Are there any that explictly support desktop applications?

# Answer
> 1 votes
Why not integrate Google Checkout? It's XML based and posts data using HTTPS, which, if your going for cross-compatibility, would work in Android too. :)

---
Tags: microtransactions
---


# Question
Title: Change opacity for texture or sprites in XNA
Is there a way to change the opacity or transparency for a texture or sprite?

# Answer
> 5 votes
Yes. You can make a semi-transparent version of any colour by multiplying it by a floating point number. For example:

```
Color halfOpacityWhite = Color.White * 0.5f;

spriteBatch.Draw(myTexture, Vector2.Zero, halfOpacityWhite);

```

# Answer
> 1 votes
Yes!

You need to use this overload of the SpriteBatch (or another overload that has the blend state option) with the blend state set to the Alpha Blend blend state. Then in the SpriteBatch.Draw method use a white color with the alpha (transparency) value you would like to have. You can use the Color.FromARGB() method to construct a semi transparent white color.

---
Tags: xna
---


title: Creating mesh at run-time

text:
# Question
Title: Creating mesh at run-time
I've a set of voxel data and I want to create a mesh out of it at run-time.

I've looked into `MeshBuilder` and `MeshHelper` but I haven't found anything useful or a good tutorial how to use them. Can anyone tell me how to create a mesh at run-time?

# Answer
I think this should answer your question: http://forums.create.msdn.com/forums/p/4751/24616.aspx

Basically you should just create a vertex and index buffer yourself (you can wrap them up in a nice class that implements IDrawable ofc).

Once you have a vertex and index buffer you can draw your model like in this MSDN article:

```
VertexBuffer  vertexBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), 8, BufferUsage.None);

vertexBuffer.SetData<VertexPositionColor>(primitiveList);

IndexBuffer  lineListIndexBuffer = new IndexBuffer(
    GraphicsDevice,
    IndexElementSize.SixteenBits,
    sizeof(short) * lineListIndices.Length,
    BufferUsage.None);

lineListIndexBuffer.SetData<short>(lineListIndices);

GraphicsDevice.Indices = lineListIndexBuffer;
GraphicsDevice.SetVertexBuffer(vertexBuffer);
GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.LineList, 0, 0, 8, 0, 7);

```
> 6 votes

# Answer
I have been working on 2D game 2y ago and had to draw shapes like thet. You could look what I have done Project - Squared.

Take a look at `GraphicsDrawer` class under `SquaredEngine.Graphics`, it will allow you to draw some basic meshes, triangles, lines, quads, ellipses, etc.

You could easily make this to work in 3D env.
> 0 votes

---
Tags: xna, c#, 3d-meshes
---


# Question
Title: Get angle in radians given a point on a circle
I'm working on a dial that rotates around a circle.

This dial should lets you mousemove anywhere in a circle to adjust the position of the dial to a point on the circle with the same angle as the click. For example, from the dial above if you clicked the spot shown in pink below I'd move the dial above that point but on the circle.

I know how to get the position of a point on a circle given a radius and an angle (in radians). That's this formula:

```
x = Cos(angle) * radius + CenterX;
y = Sin(angle) * radius + CenterY;

```

However, I am looking to do somewhat of the opposite -- I've got a click point, which I want to turn into a point on a circle (where the control knob goes). I'm trying to use this point (and a given radius) to figure out the angle in radians for it, so that I can place the control knob on the circle at the same angle.

Is there a handy formula I can use to accomplish this?

# Answer
Check out the atan2 function.

It gives you the angle between (0, 0) and (x, y), `x` and `y` being the function arguments.

**Edit:** if the center of the circle isn't (0, 0), no matter, just do this: `atan2(y - cy, x - cx)`.
> 25 votes

# Answer
You need the center of the knob and the point of the cursor along with the atan2 function. You then use it like this:

```
 angle = atan2(mouseY - knobCenterY, mouseX - knobCenterX)

```
> 8 votes

# Answer
```
Point clickPoint;
float angle = Math.atan2(clickPoint.Y - CenterY, clickPoint.X - CenterX);

```

An ok reference: http://www.mathsisfun.com/polar-cartesian-coordinates.html
> 5 votes

---
Tags: mathematics
---


# Question
Title: How can I randomly choose a monster from an array of monsters?
I have a problem dealing of how can I call the values inside the arrays correctly. First of all, I am into making an array of monsters and a set of hp for them. I made it this way:

```
string monsterlist [] = {"Imp", "Orc", "Troll", "Gnome"};
float monsterhealth [] = {5.0f, 8.0f, 9.0f, 10.0f};
int monsterlife;
int monsternumber;

```

wherein, since i can not call the variables correctly, I made a very simple way to do it, which is:

```
srand(time(0));
monsternumber = 1 + (rand() % 3);
if (monsternumber == 1)
    cout << monsterlist[1];
else if (monsternumber == 2)
    cout << monsterlist[2];
else if (monsternumber == 3)
    cout << monsterlist[3];
else if (monsternumber == 4)
    cout << monsterlist[4];

```

Is that correct? I know it might be not the proper way. This is what I wanted:

I want to create a random number generation from 1 to 4 and store that variable in monsternumber. The next thing that will happen is, if the monsternumber is equal to 1, for example, should make the monster Imp and 5.0 as its health, seen from string monsterList and monsterHealth.

Is there a proper way to make this simplier or rather the correct way of doing it?

# Answer
Your series of if/else statements can be simplified to this:

```
cout << monsterlist[monsternumber];

```

However, the line `monsternumber= 1+(rand()%3);` is problematic in the context of the rest of your program. `rand() % 3` produces a value between 0 and 2, which you then add one to. That means `monsternumber` can be from 1 to 3. It will never be zero and it will never be four.

But arrays in C++ use zero-based indexing. That means the first element in the array is at index 0 -- in order words, `monsterlist[0]` is the "Imp" string.

Similarly you don't want to try to access `monsterlist[4]` because you only have four elements in that array, so the only valid indices are 0 through 3. Thus the ideal solution to your problem is something like this:

```
string monsterlist [] = {"Imp", "Orc", "Troll", "Gnome"};
float monsterhealth [] = {5.0f, 8.0f, 9.0f, 10.0f};
int monsterlife;
int monsternumber = rand() % 4;

cout << monsterlist[monsternumber];

```
> 7 votes

# Answer
```
monsternumber = rand()%4;
cout << monsterlist[monsternumber];

```

That will keep you from having to do a large if ... else sequence.

Also, do rand()%4, or else you will never get a 4 as a result.

Other than that, it looks like it should be doing what you say you want it to do.
> 0 votes

---
Tags: c++
---


# Question
Title: Changing sprite animation depending on direction
I'm working on an android game where my sprite is controlled by a joystick. I just added an animation to my sprite with 4 rows and 3 columns:

Now I want to change the animation of my sprite depending on its direction. How do I calculate the direction of my sprite?

This is my controls:

```
public void update(MotionEvent event)
{
    // drag and drop
    if (event.getAction() == MotionEvent.ACTION_DOWN)
    {
        _dragging = true;
    }
    else if (event.getAction() == MotionEvent.ACTION_UP)
    {
        _dragging = false;
    }

    if (_dragging)
    {
        // get the pos
        _touchingPoint.x = (int) event.getX();
        _touchingPoint.y = (int) event.getY();
        // get the angle
        double angle = Math.atan2(_touchingPoint.y - inity,
                _touchingPoint.x - initx) / (Math.PI / 180);

        // move the beetle in proportion to how far
        // the joystick is dragged from its center
        _pointerPosition.y += Math.sin(angle * (Math.PI / 180))
                * (_touchingPoint.y / 70);
        _pointerPosition.x += Math.cos(angle * (Math.PI / 180))
                * (_touchingPoint.y / 70);
    }
}

```

And this is the drawing method in my sprite-class:

```
private void update()
{
    currentFrame = ++currentFrame % BMP_COLUMNS;
}

public void draw(Canvas canvas, int x, int y)
{
    update();
    int srcX = currentFrame * width;
    int srcY = 1 * height;
    Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
    Rect dst = new Rect(x, y, x + width, y + height);
    canvas.drawBitmap(bitmap, src, dst, null);
}

```

# Answer
> 1 votes
So, `_pointerPosition` seems to be the position of the sprite you're animating.

If the player was moving the sprite with say, arrow keys, you'd need to compute the sprite's direction upon moving it, and get the angle out of it using `Math.atan2()`.

But here your lucky. You already have the sprite angle available in your controls update. Let's say you store it in a \_spriteAngle variable:

```
        // (...)

        // get the angle
        double angle = Math.atan2(_touchingPoint.y - inity,
                _touchingPoint.x - initx) / (Math.PI / 180);

        // store it for animation
        _spriteAngle = angle;

        // (...)

```

Then you just pass it to your sprite drawing method, and choose your animation from it:

```
public void draw(Canvas canvas, int x, int y, double angle)
{
    update();

    int currentAnim = 0;

    // play "going up" animation if angle between 45° and 135°
    // (= in radians, PI/4 and 3PI/4)
    if ((angle > Math.PI * 0.25) && (angle <= Math.PI * 3.0 * 0.25))
    {
        animIndex = 3; // up
    }
    // play "going left" animation if angle between 135° and 225°
    // (= in radians, 3PI/4 and 5PI/4)
    else if ((angle > Math.PI * 3.0 * 0.25) && (angle <= Math.PI * 5.0 * 0.25))
    {
        animIndex = 1; // left
    }
    // play "going down" animation if angle between 225° and 315°
    // (= in radians, 5PI/4 and 7PI/4)
    else if ((angle > Math.PI * 5.0 * 0.25) && (angle <= Math.PI * 7.0 * 0.25))
    {
        animIndex = 0; // down
    }
    // play "going right" animation otherwise
    else
    {
        animIndex = 2; // right
    }

    int srcX = currentFrame * width;
    int srcY = currentAnim * height;
    Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
    Rect dst = new Rect(x, y, x + width, y + height);
    canvas.drawBitmap(bitmap, src, dst, null);
}

```

# Answer
> 0 votes
Use this to grab the angle

```
point start; // center of joystick
point end;   // current touch position
double angle =  Math.atan2(start.Y - end.Y, end.X - start.X) * 180 / Math.PI;

```

Then use something like this to draw with rotation

```
canvas.save(); // so we can restore after we rotate
canvas.rotate(angle);
canvas.drawBitmap(...);
canvas.restore();

```

See also https://stackoverflow.com/questions/3587644/sprite-rotation-in-android-using-canvas-drawbitmap-i-am-close-what-am-i-doing

---
Tags: 2d, android, physics, animation, sprites
---


# Question
Title: I'm making a board game: who should manage the player move if the board has specific locations for the players?
I know this is very specific question but imagine I have a board with spaces (like Monopoly) and a player that must go from one space to another after the dice are thrown.

So my workflow:

* Player roll dice
* After the player rolled dice
    + (from player class) space = board.getNextSpaceFromPlayer(player)
    + Move the player each step until it reach the destination
        - board.movePlayerToNextSpace(player);
        - OR
        - player.moveToSpace(space);

But how exactly do I move the player?

The board must move the player or the player move itself?

I'm trying hard to reflect how the things are in the real world but I find very hard to do so in this context.

Thanks for your help.

# Answer
> 3 votes
> The board must move the player or the player move itself?

I would say neither. The board and player are 2 objects managed by a different object that runs logic depending on the information given by the board and applied onto the player. So you move the player by the "game logic". Which depends on the information returned by the board. Which in this scenario could be the cell(A space on your board) relatively from the players current position to the next calculated cell determined by the die. A Cell holds various information, like which player owns it ( if we are talking about monopoly) trough id. The condition the player must meet before progressing any further etc.

Your player could simply be a sprite, and by using an additional object you can keep track of stats like id and position. ( although you could just program the sprite and the stats into one object) This information is passed onto the board itself and processed internally to handle its own information. It then gives information back to the "game logic" and the player is moved by the conditions that are given.

So basically :

```
GameLogicObject ( or simply put BoardGame)
    |
    \-->Board //contains position grid, etc.
    |
    \-->playerList[] ( using id 0, 1 , 2 and 3 to access the right player
        information in combination with currentPlayer++ after each
        round depending on the amount of players and looped back to 0)
    |
    \-->Other properties
       Game stats like current gameState, Time etc.

```

# Answer
> 1 votes
Some times it is hard to determine who is the real actor.

Why not saving the players tokens in the player itself so that each player has a reference to it's tokens (even if you only have one) then let the board roll a dice.

The board itself (being a representation of the actual game rules) should be called to move a specific token (by players choice if there are more than one) with a specific dice roll.

So in a monopoly style game it would be the only token a player has wich is moved forward for a given ammount of fields. In a Ludo game the player would chose wich token is is, that he wants to move and submit it to the board class.

Why do I put the dice roll into the board? Because it depends on the boardgame itself what dice is it to use or if the actual player has to roll the dice more than once (because of special game rules (e.g. prison in monopoly)

So your Player would actually be a class that holds every information about a player. Name, Points, Money, game tokens that belong to him etc. . While the board says whose turn it is and what options are open to that player.

How you move your game tokens is up to the game rules. Is it important that a player cant cross specific fields without stopping, then you should have a method that moves that token only one field at a time to check if such a field has been crossed.

If it isn't that important you could just say "move my game token for 4 fields in that direction".

You could even go all the way down to writing a standard board game Interface that you can use to implement several different board games wich have a more or less linear game plan layout (monopoly, ludo, game of life).

# Answer
> 0 votes
It is a rather unique relationship between the board and the player, isn't it?

In this case, it seems that the Board contains Spaces, and the Player can inhabit a particular Space on the Board.

I'd think it makes more sense for the Player to move itself, because the Player is the one that contains the reference to the particular Space that it inhabits.

However, that also means that the Player will need to ask either the Space it currently inhabits or the Board for a reference to the next Space on the Board.

# Answer
> 0 votes
In order to not limit yourself in the future, you may wish to trigger a move of the piece from the players action.

However, a player class should not contain any methods such as "movePiece", but instead they should have methods like "clickedGameSpace", or something more player-centric.

It's your board class that should be acting upon the board, not the player. However, the player would probably be best as the initiator of the move, even if that requires some abstraction to convert from a "gamespace click" to a "piece move"

You may even wish to have the Player class be completely uncoupled from the board. Instead of clicking "spaces", it simply picks options... but there are many ways to implement this which could be considered good practice.

---
Tags: 2d, strategy
---


# Question
Title: Collision between AnimatedSprite and Rectangle null pointer error
I'm trying to detect a collision between an AnimatedSprite and the Rectangle floor. When they collide, I want the sprite to be removed. However, I keep getting a null pointer error. Am I doing this the wrong way?

Inside my add face function. `face` is an AnimatedSprite created, and `ground` is a rectangle.

```
this.mScene.registerUpdateHandler(new IUpdateHandler() {
            @Override
            public void reset() { }

            @Override
            public void onUpdate(final float pSecondsElapsed) {
                    if(face.collidesWith(ground)) {
                           Debug.d("Contact!");
                           removeFace(face);
                    }
            }
    });

```

`removeFace()` is:

```
private void removeFace(final AnimatedSprite face) {
    final PhysicsConnector facePhysicsConnector = this.mPhysicsWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(face);

    this.mPhysicsWorld.unregisterPhysicsConnector(facePhysicsConnector);
    this.mPhysicsWorld.destroyBody(facePhysicsConnector.getBody());

    this.mScene.unregisterTouchArea(face);
    this.mScene.detachChild(face);

    System.gc();
}

```

The null pointer exception is inside `removeFace()`

# Answer
> 2 votes
Look at the stack trace it will tell you exactly which line has the null pointer exception. You need to invest in learning to use the debugger too, these are simple problems to debug and you can solve your own problems much faster than waiting for a reply here.

From your code I'm assuming that

```
this.mPhysicsWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(face)

```

is returning `null` because it's unable to find the face you specify. So it could easily throw a null pointer exception when it reaches: `facePhysicsConnector.getBody()`. Since you can't access a method of a null object.

---
Tags: android, andengine
---


title: Why is std::atan2 returning -0.0?

text:
# Question
Title: Why is std::atan2 returning -0.0?
Really? Negative zero?!

```
double Vector2D::GetFacingAngle(const Vector2D& target, const Vector2D& source) {
    a2de::Vector2D facingVec(Vector2D(source) - Vector2D(target));

    //Negating 'y' argument to account for flipped nature of 'y' screen coordinates.
    double result = std::atan2(-facingVec.GetY(), facingVec.GetX());

    //Which causes -0.0 as a possible result when source is right of target at the same 'y' coordinate.
    if(a2de::Math::IsEqual(result, -0.0)) return 0.0;
    return result;
}

```

Is this a common behavior? (Similar to subtracting 'y' coordinates for 'up' movement in screen coordinates contrary to Cartesian coordinates.)

# Answer
What you're seeing is a signed zero, which is a possibility in certain systems of number representation, including the IEEE standard used for C++ floating point representation, even though it isn't really a thing in "ordinary" mathematics.

The link contains some notes on behavior and handling of the occurrence, although beyond that it's not entirely clear to me what you're asking, specifically -- it's not a bug with `atan2` though. In fact, the wiki article on the function notes that the relevant Intel assembly instruction (`FPATAN`), which you're likely generating here, will produce a negative zero when first parameter in negative zero but the second is positive zero. Your explicit negation of your vector's Y component could easily produce such a scenario.
> 4 votes

---
Tags: c++, mathematics
---


# Question
Title: Are there any good ways to know if a resource is patented trademark or illegal to use?
This is something that I worried about for a long time. While making games, it is hard to tell for sure if any of the resources are copyrighted unless a person is clearly aware that they are to a like to an image that have known in certain work done. I wanted to make a 2D MMO, that in certain ways might be similar to *"Pokémon"*. I did not want to make an illegal game, but it is just that there are certain elements that I want in the game which are similar to those in *"Pokémon"*. I also wanted to possibly sell the features of it, if the project succeeds and works out all well. What exactly are some ways that I can find out for sure if images that I am using are illegal to use or not.

The element which I am worried about in the game which I was planning to make was about creature battling and summoning. Thankfully, game concepts cannot be copyrighted, but I did not want to take or use images that were exactly like those in *"Pokémon"*, and I wanted to make a game that is very different in many ways. I might have wanted to use creatures in a similar cartoon fashion that is used in *"Pokémon"*. This has been somewhat of a concern, to me, though as about the legal issues possibly.

# Answer
> 5 votes
Every "work" is protected unless otherwise specified. Any kind of resources are a work, so are the designs themselves (so you can't make a creature of yours look like Pikachu for example). The code is a work, too, but you won't be able to look into the code of almost any game anyway.

With trademarks you wont have a problem unless you use the names/places/worlds of something else.

So... don't use any art, any (visual) designs, any names and any other kind of resource (music, maps, sound effects, \[...\]) from someone else's games and you are fine.

# Answer
> 2 votes
This is totally an emotional and not a legal answer, but any time you're thinking of using something, ask yourself this: If you had created the original and someone else was about to do something with it that you're contemplating, would it be OK with you?

If yes, then well maybe it's OK.

If no, then ask yourself why it would bother you, and if this isn't something you should consider in your own decisions.

# Answer
> -8 votes
As long as you don't use any pokemons name or poke-something, or any graphics like pokeballs. You should be fine. Happy coding!

---
Tags: legal
---


# Question
Title: Collision detection and response in an Entity System
More fun with an ES...

Currently, I have a few systems:

* Renderer (Renderable attribute, Transform attribute)
* Motion (Movable attribute, Transform attribute, Renderable attribute \[for bounding boxes, etc\])
* Input (InputReceiver attribute)
* etc.

I'm adding collision detection. My first thought was to add a new system that performs collision. It makes sense to me to keep this isolated from the `Motion` system since not all things that move or are animated necessarily participate in collision detection - cameras, fog, etc. - but it seems that `Collision` and `Motion` are interdependent.

When `Motion` moves an entity, the transformation needs to be validated with `Collision`, and the movement either cancelled, or adjusted (bouncing, stopping at a wall, etc.).

An alternative would be to create a Collidable attribute that maintains a reference to a collision object - kd-tree, octree, etc. that is shared among entities that can collide with one another. The `Motion` system would then check for that attribute, and use it to check or adjust movement.

From a code perspective, that's an acceptable solution. However, from an ECS architecture point of view, it seems that it's pushing logic into the `Motion` system that doesn't apply to all of the entities that have a `Movable` attribute.

I could also store a motion vector in the `Movable` attribute, and have the `Collider` system adjust `Transform` as needed, but that'll involve duplicating functionality between `Motion` and `Collider`, or a callback from `Collider` to `Motion` with some data about the collision location and surface data for bounce/reflection, etc.

This may fall under the heading of "special case hack" but I'd like to get some input from those that have handled this before without creating a ton of edge case code.

**The Question** What's a good way to avoid tight coupling between motion and collision systems when it seems that they require knowledge of each other?

# Answer
You're overthinking it. In my engine, which also uses an entity-component system, every `GameObject` can have a pointer to a `ModuleCollision`.

What happens when the game updates:

* Scene updates all objects it holds. It calls the `Update` function for each `GameObject`.
* Inside the `Update` function, each `GameObject` *only* updates its speed and direction, *not* its position.
* `GameObject` uploads its current position, speed and direction to its `ModuleCollision`, if one is available.
* Scene does collision checking on a `ModuleCollision` basis.
* Scene calls the `UpdatePost` function on each `GameObject`. If the object has a collision module, it fetches the updated position, speed and direction from the collision module. The position is updated with the speed and direction.
* The `GameObject` constructs a final 3x3 matrix out of its position and heading.

Yes, there is some duplication of state, but that's okay. Doing collision handling on a `ModuleCollision` is the best way to go about it, because otherwise you would have to check each `GameObject` to see if it has a `ModuleCollision` handle.
> 7 votes

# Answer
I would do it like this...

Have three systems:

1. Movement system
2. Acceleration system
3. Collision system

The movement system applies velocities to positions. The acceleration system applies forces to velocities. The collision system detects collisions and applies the forces in the right directions, or, if you want crude collisions, directly alters the velocities.

For example, you could calculate the angle between the collisions using atan2, and then use that to apply the correct forces/velocities the bodies.

Have the collision detection system broadcast messages if needed too.
> 3 votes

---
Tags: collision-detection, entity-system
---


# Question
Title: To what extent it is legal to declare support of third party commercial products' assets?
Is it legal to say that *MyGame* supports other (specific) games' textures, sounds and models?

I'd like to get involved into an open source game project and implement support for *Quake's weapon models* (for example), but the owners of the project don't know about the legal aspect of it, so I'm asking here.

# Answer
It depends on the third party. Valve's SDK, for example, prohibits use of it for anything other than mods running on the Half Life engines, so if you were to use their formats you would be in violation. Other third parties may have different or similar terms.
> 2 votes

# Answer
I believe the information provided by ID software with their code releases would be the closest thing to actually asking ID yourself

> ID Software github - readme.txt for Quake
>
> All of the Quake data files remain copyrighted and licensed under the original terms, so you cannot redistribute data from the original game, but if you do a true total conversion, you can create a standalone game based on this code.
>
> --- snip ---
>
> You can still download one of the original quake demos and use that data with the code, but there are restrictions on the redistribution of the demo data.
>
> If you never actually bought a complete version of Quake, you might want to rummage around in a local software bargain bin for one of the originals, or perhaps find a copy of the "Quake: the offering" boxed set with both mission packs.

The only company that can truly answer your question would be ID software, if they consider your game to be in violation of their copyrights then they will most likely take legal action regardless of what anyone here tells you. On the other hand, they have released the source code of Quake in a manner that allows you to modify it as long as you don't distribute the other files with your modifications.

---

You may wish to consider that by making the game "borrow" models from another game installed on the users computer you will never be able to make a full installation that does not require that game. In short, you will artificially shrink your potential user base, all to save yourself the relatively short time it would take to make a suitable weapon (and projectile) model in a 3D program.

**Personally I would use Blender and make a quick weapon myself, even if it looks crude it would be safe to use and could be upgraded in the future without any legal dilemmas.**
> 4 votes

# Answer
I've seen people doing this by not including the models, textures etc in game.

IANAL but I don't see how supporting other people's textures etc can be illegal.

Shipping it with your game without prior permission probably is illegal (unless otherwise stated).

It's a faff for users to have to provide them, so having a tool to make import easy would be a winner.

I don't think you're going to get the answer you want because, as mh01 said, the different companies Valve, ID etc don't share a common licence regarding usage of their models.

You're either going to need to evaluate them on a company by company basis. Or otherwise implement support / compatibility without including models.

Again IANAL but it would make sense to me that the responsibility transfers to the user of the app / game if they find models themselves and put them in the right place.
> 2 votes

# Answer
A couple of examples:

* Irrlicht 3d engine openly claims support for various Quake formats, among others
* Blender openly claims support for a multitude of model formats, including Quake's md2
* Assimp asset loading library openly claims support for Quake's models as well as others

You should be safe if you claim support for other product's asset formats. Directly claiming support for other game's data might be ok too, but the user could be in violation depending on the EULA and such - you yourself commented that many allow personal use, so check it for each one in your mind. Examples of open-source games that depend on the original data are Arx Libertatis and OpenMW.

Regarding implementation, I think the main issue is whether the file formats contain patented features in which case it would be illegal to implement in some countries. This is most frequently encountered in formats that attempt some kind of compression, such as audio/video files.
> 1 votes

---
Tags: legal, assets
---


# Question
Title: Trouble programming JInput for game controller
Due to lack of reasonable documentation, I have not been able to program inputs for using a game controller. The most I have ever found was how to detect if a controller is found and what it's name is. Does anyone know of a reliable tutorial on how to program controller buttons to perform any actions?

# Answer
Maybe this Video will help you: http://www.youtube.com/watch?v=lIdmpaWf9Eo .
> 0 votes

---
Tags: java, lwjgl, controllers
---


# Question
Title: Can I use the ENet library in a commercial game?
I have some problems understanding ENet's license. It's not the zlib license as far as I know, but it seems like it's not GPL either. I'm not a native English speaker and I can't understand what the license exactly is.

Can I use ENet for a commercial game? If yes, do I need to mention that I used ENet *and* do I need to deliver ENet's license with my game?

I have no problem with mentioning that I use ENet in my credits, but ENet's license delivering thing seems just stupid and not-understable to me.

# Answer
> 4 votes
It's the MIT license. You can do anything with MIT licensed software as long as you include its license somewhere in the distribution (it gives credit and disclaims warranty for the MIT licensed part). So commercial software is ok, and your product can be closed-source if you want (so you are *not* forced to use MIT license for your own product).

---
Tags: licensing, commercial
---


# Question
Title: Which models and scene to use for a dungeon game?
I use jme3 with some builtin models and scenes and I've managed to put together a third person 3D scene.

I now want to program some attack and/or fights and I think that skeleton warriors and/or zombies will be ideal but how to get them? I don't know modelling, do I have to learn modelling, buy zombie and skeleton models, make them myself, download models from somewhere or something else? I'm currently using a builtin example scene that is like Quake 3 where I placed the ninja so that he can walk around and collission detection works which was the main project. Now the ninja can make an attack if I press the mouse button and he can jump if I press the space button and WASD controls the walking which is sort of slow but smooth. How can I try with another scene that is more like a dungeon? Is it the same as with the models, I must either design my own scene in a 3D program e.g. blender or use a scene like I do which is freely available?

I tried using a worldforge model for a goblin but it didn't render correctly:

```
com.jme3.asset.AssetLoadException: An exception has occured while loading asset: objects/creatures/goblin/textures/green/ogre.material
    at com.jme3.asset.DesktopAssetManager.loadAsset(DesktopAssetManager.java:284)
    at com.jme3.material.Material.<init>(Material.java:116)
    at adventure.TownWorld.simpleInitApp(TownWorld.java:338)
    at com.jme3.app.SimpleApplication.initialize(SimpleApplication.java:225)
    at com.jme3.system.lwjgl.LwjglAbstractDisplay.initInThread(LwjglAbstractDisplay.java:129)
    at com.jme3.system.lwjgl.LwjglAbstractDisplay.run(LwjglAbstractDisplay.java:205)
    at java.lang.Thread.run(Thread.java:679)
Caused by: java.io.IOException: Must specify MaterialExtensionSet when loading
Ogre3D materials with extended materials
    at com.jme3.scene.plugins.ogre.MaterialLoader.load(MaterialLoader.java:440)
    at com.jme3.scene.plugins.ogre.MaterialLoader.load(MaterialLoader.java:465)
    at com.jme3.asset.DesktopAssetManager.loadAsset(DesktopAssetManager.java:282)
    ... 6 more

```

What does it mean? The offending code is

```
    Spatial model3 = assetManager
            .loadModel("objects/creatures/goblin/goblin.mesh.xml");
     Material mat_stl = new Material(assetManager, "objects/creatures/goblin/textures/green/ogre.material");

     mat_stl.setTexture("Green", assetManager.loadTexture("objects/creatures/goblin/textures/green/D.png"));

             model3.setMaterial(mat_stl);

```

How should I use materials / textures for a model such as above? Now the mesh loads but there is no material and I don't know how to connect any eventual animation that come with the worldforge model.

I would really like to use skeleton or zombies, can you tell me how I should do it?

Any other comments / advice?

# Answer
> 2 votes
Try opengameart.org. There are some great models there. Mind the licenses though. :)

---
Tags: 3d, models, ogre, jmonkeyengine, scene
---


# Question
Title: Shader authoring/editing tools for GLSL ES
Since Render Monkey has been discontinued (perhaps due to the complexity of today's shading languages), there are few successors that can match its functionality. Is there any useful tool for material editing aimed at developers and artists alike, but concentrated (or with substantial support for) on embedded GLSL shaders?

Render Monkey itself wasn't that flexible (I'm not aware if it allowed the usage of several textures, each with its own set of texture coordinates - plus, it didn't seem to be that intuitive either). Apart from complete engines, is there such a stand-alone tool that can be used together with a stand-alone engine (able to interface with a custom application)?

# Answer
I used RenderMonkey ~6 months ago and didn't have any problem, although the shaders I made were pretty simple.

It looks like the only decent succesors are Mali GPU Shader Development Studio and PVRShaman. The latter only works with PowerVR FX effects and POD geometry objects, so maybe it's not enough flexible for your requirements.
> 1 votes

---
Tags: shaders, opengl-es, glsl, tools
---


title: Drawing at negative coordinates in XNA?

text:
# Question
Title: Drawing at negative coordinates in XNA?
I am trying to make a 2D isometric RPG and I kind of hit a wall when it comes to lighting. I was thinking of using shaders, if I manage to understand them.The problem I am anticipating is the presence of light sources outside the screen.In order to calculate shadows and so on I'd still need to have those objects rendered even if they're offscreen or else light would pop in and out if I move the view around the map. I was thinking of drawing the entire level, not just what is seen, but that would mean drawing at negative and outside the view coordinates.Does that work or I should seek a better, more efficient alternative?

# Answer
> 3 votes
If you just want to know if drawing outside of the bounds is possible, yes it is. The GPU will cull what is not visible and keep what is onscreen. Really, you should be using a transform matrix on your spriteBatch calls though; draw everything via its world position and then transform it to view cordinates using a matrix transform.

---
Tags: xna, 2d, shaders, isometric, lighting
---


# Question
Title: 1 kb swf file created when building to flash in unity
I am trying to build a project in flash that I have made. It goes through its building process, but when it is done the swf file that it creates is 1 kb in size. I am not sure what I am doing wrong or what is going on. I have built to flash before and never ran into this problem until recently.

# Answer
> 2 votes
Hey I figured out a solution that works. All I did was switch the platform to something else then switched back to flash and was able to get it to work

---
Tags: unity, flash
---


# Question
Title: Tools need to for low poly model, texture making & lighting in unity3d (iOS)
I am new to unity3d, i want to create a 3d game i have a team of 3d designers and programmers. My question which software should we use for modelling, texture making and advanced lighting for mobile to enhance game performance.

Thanks

# Answer
> 3 votes
Ultimately I would assume that your 3d modelers would suggest which software they prefer, as forcing them to use something different would be counter-productive. As for advanced lighting, Unity can take care of that. And for textures, I would say to check with the designers.

The free alternatives:

* Blender - 3D modelling and some basic texturing
* GIMP - Texturing/Bump Maps/Etc

---
Tags: iphone, unity, lighting, low-poly
---


title: Why four buttons rather than two?

text:
# Question
Title: Why four buttons rather than two?
I'm curious that most console controllers released these days - and all handheld consoles - contain four main buttons rather than two. Obviously increases in processing power, graphics engines etc, have allowed for more complex games, but is there an argument to be made that two buttons are really enough to create some great games? In other words, would someone releasing a new handheld console on the market today be foolish not to include four?

# Answer
Two are enough for some really great games. For other really great games, two aren't enough. When designing a default control system, all other things being equal, you want it as inclusive as possible.

But then - if four are better, why wouldn't six be better still? (for example, the late-era Genesis and Saturn pads had six buttons). Four's a magic number because you can have your thumb resting between them and easily reach any button without having to consider absolute position, and reasonably comfortably hit most combinations of two (for example, holding X to run/shoot and pressing A to jump). Having six face buttons isn't just 50% more complex - it means a certain way of interacting comfortably and intuitively with the controller doesn't work any more. So, for face buttons, four turns out to be a soft limit for general usage.

Contrast this with the Neo-Geo, which also had four buttons - but there, unlike modern pads, they were arranged in a line. That's because it used an arcade stick, and each finger laid naturally on each button. Going down to three buttons wouldn't change the control paradigm: going up to five would. So, again, four buttons were a natural soft limit, but here for a different reason on a different design of controller.

Why four? Because, in this context, it's not much more than two, but six is a lot more than four.
> 18 votes

# Answer
It's easier to use a button for one action than using a combination of buttons. Double Dragon for the NES made you hit A + B to jump. While A and B are also Kicking and Punching. Logically it's less intuitive if you use certain buttons for different unrelated actions. As a player you get accustomed to the layout, but it is certainly not better than having a third button to jump.

Of course this completely depends on the requirements of the game. Some games only need two buttons. But limiting game-designers to only two buttons is counter-intuitive.

If you take zelda : links awakening and link to the past for example. Link to the past had a third button to perform certain actions. While keeping sword mapped to 'B' and Item use to 'Y'. 'A' was used for various actions like pulling, talk, running etc. In links awakening you had to swap out items to 'A' and 'B'. You could even swap out your sword. Might be handy, but unnecessary if there were more buttons.

It really comes down to the gamedesign.
> 5 votes

# Answer
If a game developer chooses to use only two of the four available main press buttons, that is currently an option.

Other games may choose to utilize all four, that is also an option.

Limiting the game designer by only offering two main input buttons is simply bad design. Yes, a great game may only need a single input, but that does not mean all games should.
> 4 votes

# Answer
> but is there an argument to be made that two buttons are really enough to create some great games

A simple top X list of NES or Gameboy games would be argument enough that you can make great games with two buttons (plus directional control).

But there is also plenty of games that would be either impossible to make for 2 button input, or would be so cumbersome to play they would no longer be considered top X material.

In short, having few or many buttons does not mean your game will be a hit or a miss, the game itself and how well it works with the controls your target system has to offer is more important than the number of buttons the player has to use.
> 1 votes

# Answer
My gameboy micro (if that's an old enough console ^^) hasn't got two but six buttons (+ the 'cross')

They are : A,B,L,R, select and start
> 0 votes

---
Tags: controllers
---


title: Books for designing virtual economy

text:
# Question
Title: Books for designing virtual economy
I am wondering if there are any books on designing virtual economies.

I have encountered some books which have a few lines or paragraphs written about virtual economies, but they mainly highlight how difficult it is to design and control a virtual economy; they don't give any useful advice on how to design a virtual economy.

# Answer
I've been doing a lot of research on this topic in the past several months and have gathered quite a bit of resources that you might find useful. Although I haven't come across an actual book about it, these articles are pretty long (and comes in several parts) so they are pretty close :)

Take a look at these to get you started:

Virtual Economic Theory: How MMOs Really Work \- Simon Ludgate

The F-Words of MMORPGs: Fairness \- Simon Ludgate

The F-Words Of MMOs: Faucets \- Simon Ludgate

Sell Your Money! \- Simon Ludgate

Designing For Free Takes More Than 'Just' Game Design \- Soren Johnson

MMORPG: Luck or Grind? \- Simon Ludgate

MMOs: Just a Matter of Time? \- Simon Ludgate

Tips on Developing an MMO Economy, Part I \- Radu Privantu

Edit: Removed a dead link.
> 14 votes

# Answer
There is a interesting blog article with a few general ideas to get you started.

I would say on the most basic level you will need money pools and money sinks. (IE a way to earn money and a way to lose it (preferably one that unavoidable).

I did notice a few suggestions on other forums that suggest making everything craftable and controlling only the basic resources directly (Random placements ores, variable drop rates, spawn points moving (to avoid camping). UBER bosses dropping UBER resources not gear so those that like to craft can still make a living by working for the ones that like to fight :)

Another suggestion was to stop higher level players getting hold of lower level resources directly but making them need it for crafting to ensure the new players have ways to make gold.

In general it depends on the game and the level of complexity you want. You have the economist's wet dream at your fingertips you can see every single transaction,trade and event that occurs.

You could dynamically change prices according to the items demand and supply and players trading prices.

As for the actual question i found a answer here regarding users suggestions however can't recommend any myself (I haven't read them).

Hope this helps
> 3 votes

---
Tags: books, economy
---


# Question
Title: Using multiple sprite sheets for same object AndEnginge
I have multiple sprite sheets for my object(Parrot) like eating, moving left to right, right to left and much more. I am using AndEngine gles2.0. How should I implement it? Every time I have to use different sprite sheet, detach previous one and on same location add new one. This is going to be hectic!

Anyone here who already implemented this kind of scenario? If I use single sprite sheet for every animation it size will increase and it will throw a exception of out of memory!

# Answer
> 1 votes
This is my code to perform animations of different sprite sheets.

```
public void performEatingAnimation(Bird b) {
    float x = b.getSelectedAnimatedsprite().getX();
    float y = b.getSelectedAnimatedsprite().getY();
    b.getSelectedAnimatedsprite().setVisible(false);

    b.getSelectedAnimatedsprite().detachSelf();
    b.setSelectedAnimatedsprite(b.getEatingAnimatedsprite());

    attachObjectWithNewPosition(b.getSelectedAnimatedsprite(), x, y);
    b.getSelectedAnimatedsprite().animate(60, 2);

}

public void performWalkAnimation(Bird b) {
    float x = b.getSelectedAnimatedsprite().getX();
    float y = b.getSelectedAnimatedsprite().getY();
    b.getSelectedAnimatedsprite().setVisible(false);

    b.getSelectedAnimatedsprite().detachSelf();
    b.setSelectedAnimatedsprite(b.getWalkingAnimatedsprite());

    attachObjectWithNewPosition(b.getSelectedAnimatedsprite(), x, y);
    b.getSelectedAnimatedsprite().animate(60, 0)
 }

```

And here is my setSelected method to perform a deepCopy of AnimatedSprite.

```
public void setSelectedAnimatedsprite(AnimatedSprite selectedAnimatedsprite) {
    AnimatedSprite sprite = new AnimatedSprite(
            selectedAnimatedsprite.getX(), selectedAnimatedsprite.getY(),
            selectedAnimatedsprite.getTiledTextureRegion().deepCopy(),
            selectedAnimatedsprite.getVertexBufferObjectManager());

    this.selectedAnimatedsprite = sprite;
}

```

# Answer
> 1 votes
The only reason you would want to have a "left to right" and vice versa animaton is if they are actually different. If this is not the case you simply flip your sprite on the y axis to -1 and back to 1 depending on the direction your sprite is walking in. If he is normally facing right, -1 will make him face left.

Usually a full character animation fits onto one sprite sheet.
Try TexturePacker ( semi-free)
or
libgdxs texturepacker (free)

The files these packers generate could surely be used in AndEngine. I also recommand looking at LibGDX for gamedevelopment on Android. It takes a bit more effort to setup but in the end it gives you far more freedom.

> If I use single sprite sheet for every animation it size will increase and it will throw a exception of virtual memory exceed!

You need to optimize your TextureAtlas/SpriteSheet. Like I said, keep the animations for both directions to a single direction and just flip your sprite. You can also reduce the quality of your sheet to a point you won't notice and save up on memory use.

Edit: As to your comment below: You simply need to bind/swap textures then. I suggest creating a class with animation properties ( like the amount of frames, framerate, rectangle size, etc) that also holds the sprite sheet texture. Then you have animation player class that holds all of these animation objects. This is just an example and not the absolute way ( I don't know about the build in sprite sheet application of AndEngine, just throwing a bone here):

```
class SingleRowSpriteSheet{
  private MySpriteSheetTexture sheet;
  private Rect rect;
  private int frameRate;
  private int frames;
  private currentFrame;

  public MySpriteSheetTexture getSheet(){return sheet;);
  public drawOnTo(MyTextureTarget target); // Draws on your texture, also binds the texture if it's not already done.
  public update(); // update currentFrame and looping
}

```

\

```
 import java.util.*;
class SingleRowAnimator{
   private MyTextureTarget target; // don't know the texture class for AndEngine. but it's the reference to the texture of your sprite;

   private SingleRowSpriteSheet currentAnimation;
   private HashMap map;
   //Using a hash map so that you can call animations by name
   public void animateTo(MyTextureTarget texture);
   public void addAnimation(String name, SingleRowSpriteSheet srss){
      map.put(name,srss)
   };

   public void playAnimation(String name, int atFrame){
     currentAnimation = map.get(name);
   };

   public void update(){

          // do update stuff here
         currentAnimation.update();
         currentAnimation.drawOnTo(target) // draws onto your target.

   }
   etc.
}

```

SingleRowAnimator would be an aggregated object put in your entity object. Then when you need to change animation simply call: playAnimation;

This is just a rough idea of how you COULD do it. I hope this helps.

edit: Just noticed that these 2 class names are a bit misleading. But just look at the idea.

edit: What I don't get is, even for this, you would need to load every SpriteSheet into your game. So to my idea this would also cause a memory error. Make sure you are working with textures that are sized for your target resolution. Use bilinear/trilinear filtering to smooth out the pixels.

As an alternative to my solution, see if there is a way to copy pixels from a spritesheet unto your texture target.

# Answer
> 0 votes
As of reading my own comment. It could very well be that you create new textures for every object in your game.

Always have one pool of textures / One place the texture is read from and let your sprites reference/point to it.

It simply sounds impossible for ONE spritesheet to make your device go out of memory. Most games today certainly have at least 2 to n spritesheets.

---
Tags: android, sprites, andengine, opengl-es2, spritesheet
---


title: 2D Tile Based Particle Collisions

text:
# Question
Title: 2D Tile Based Particle Collisions
I have a basic 2D particle system and I'm now looking to implement collisions, however I'm not sure on what the best way to do it is. My game is tile based and runs in XNA Game Studio 4.0. I've seen the platformer sample which has the player's collisions system working like this:

```
for(int x = leftTile; x <= rightTile; x++)
{
    for(int y = topTile; y <= bottomTile; y++)
    {
        if(TileIsSolid(x, y))
        {
            //Resolve...
        }
    }
}

```

But I don't know if this is feasible to run on 300 particles at one time, and it needs it support tiny fast moving objects such as bullets from a weapon. So how do I go about implementing 2D tile based particle collisions?

# Answer
> 0 votes
You still need to perform the checks.

There are several ways of doing this. You certainly don't want to go the dumb way, that is, checking each pair of objects in the scene. No, implement something called a quadtree. It's a space-partitioning algorithm that greatly increases the speed and efficiency of collision detection.

---
Tags: xna, collision-detection, tiles, tilemap, particles
---


# Question
Title: Sampler referencing in HLSL - Sampler parameter must come from a literal expression
The following method works fine when referencing a sampler in HLSL

```
    float3 P = lightScreenPos;
sampler ShadowSampler = DPFrontShadowSampler;
float depth;

if (alpha >= 0.5f)
{
    // Reference the correct sampler
    ShadowSampler = DPFrontShadowSampler;

    // Front hemisphere 'P0'
    P.z = P.z + 1.0;
    P.x = P.x / P.z;
    P.y = P.y / P.z;
    P.z = lightLength / LightAttenuation.z;

    // Rescale viewport to be [0, 1] (texture coordinate space)
    P.x = 0.5f * P.x + 0.5f;
    P.y = -0.5f * P.y + 0.5f;

    depth = tex2D(ShadowSampler, P.xy).x;
    depth = 1.0 - depth;
}
else
{
    // Reference the correct sampler
    ShadowSampler = DPBackShadowSampler;

    // Back hemisphere 'P1'
    P.z = 1.0 - P.z;
    P.x = P.x / P.z;
    P.y = P.y / P.z;
    P.z = lightLength / LightAttenuation.z;

    // Rescale viewport to be [0, 1] (texture coordinate space)
    P.x = 0.5f * P.x + 0.5f;
    P.y = -0.5f * P.y + 0.5f;

    depth = tex2D(ShadowSampler, P.xy).x;
    depth = 1.0 - depth;
}

// [Standard Depth Calculation]
float mydepth = P.z;
shadow = depth + Bias.x < mydepth ? 0.0f : 1.0f;

```

If I try and do anything with the sampler reference outside the if statement then I get the following error:

*Sampler parameter must come from a literal expression*

This code demonstrates that

```
    float3 P = lightScreenPos;
sampler ShadowSampler = DPFrontShadowSampler;

if (alpha >= 0.5f)
{
    // Reference the correct sampler
    ShadowSampler = DPFrontShadowSampler;

    // Front hemisphere 'P0'
    P.z = P.z + 1.0;
    P.x = P.x / P.z;
    P.y = P.y / P.z;
    P.z = lightLength / LightAttenuation.z;
}
else
{
    // Reference the correct sampler
    ShadowSampler = DPBackShadowSampler;

    // Back hemisphere 'P1'
    P.z = 1.0 - P.z;
    P.x = P.x / P.z;
    P.y = P.y / P.z;
    P.z = lightLength / LightAttenuation.z;
}

// Rescale viewport to be [0, 1] (texture coordinate space)
P.x = 0.5f * P.x + 0.5f;
P.y = -0.5f * P.y + 0.5f;

// [Standard Depth Calculation]
float depth = tex2D(ShadowSampler, P.xy).x;
depth = 1.0 - depth;
float mydepth = P.z;
shadow = depth + Bias.x < mydepth ? 0.0f : 1.0f;

```

How can I reference the sampler in this manner without triggering the error?

# Answer
> 1 votes
You can use this in your pixel shader:

```
sampler NormalSampler : register(s1);

```

And this in your C#:

```
graphics.GraphicsDevice.Textures[1] = normalTexture;

```

---
Tags: xna, hlsl
---


# Question
Title: SDL surface inside another GUI component?
Is there a way to host an SDL surface inside another GUI component so that SDL is not at the top-level? For instance, could I put an SDL surface inside a Java JPanel or other widget?

# Answer
The SDL website has several examples of how to do this: http://sdl.beuc.net/sdl.wiki/FAQ\_GUI

I'm not sure about Java, but you can definitely do it in C/C++ with GTK+
> 2 votes

---
Tags: sdl
---


title: How many developers are there?

text:
# Question
Title: How many developers are there?
We game developers appear to be a pretty big community. But how big is that community exactly?

How many developers, professional as well as amateur, are working on games all around the world? Do sources to get that number even exist?

# Answer
Best figure i found is here I not sure how accurate it is tho but certainly looks cool.
> 8 votes

# Answer
At time of writing: 15,118. (Source)
> 3 votes

# Answer
I think that is not posible to determinate how much people are developing games as a hobby or for a living, beacose not every one publishes he's creation or tells about it. I have developed like 3 games so far and only one of them is published.
> 0 votes

---
Tags: game-industry
---


# Question
Title: OpenGL ES 2.0 Best Practices / Architecture Guide
I've recently started working with OpenGL (ES 2.0) on the Android. While there is lots of documentation about the basics, I can't seem to find much about the overall architecture of OpenGL. In particular, while I see how a Program works, shaders are linked, and vertices are loaded, I can't find any indication of how this should be used to create entire scenes.

That is, does one create multiple programs, reuse the programs, create multiple indexes, try to share textures/shaders, etc. What I'm looking for are some solid references that explain the trade-offs, and intended use, of these functions in the production of scenes. The various Android docs, and OpenGL docs also hint at several limitations in using the API, but don't give concrete information in many cases.

*I understand this may be a bit subjective, but I really can't find anything useful on this topic by searching. I'm unsure where else to ask and I believe that concrete useful answers can be given.*

# Answer
> 3 votes
I would suggest you start doing some reading. The book Game Engine Architecture by Jason Gregory was very helpful in giving me an understanding of the relationship between a game engine and the rendering pipeline.

First, you need to understand the role of the rendering pipeline of a modern video card (which, for the most part, is what OpenGL is designed to provide access to). In this pipeline, the video card primarily assembles lists of vertices into triangles and turns these into pixels on the screen. While that is a very gross generalization, it serves to point out that the OpenGL API is designed to be very low level and provide flexible access to the functions of the video card.

The relationship between this API and your game / game engine depends a lot on what kind of abstractions you want to make. For example, if you're making a fairly simple 2D game, you may only need a very simple abstraction (something that draws a texture to a quad could be the only thing you need). If you have a more complex 3D game with a free moving camera, numerous lights, and lots of models with various shading techniques, you'll need a lot more abstraction.

I know firsthand how difficult it can be to work on both high-level game design tasks and low-level engine design / rendering routines simultaneously. It can be very difficult to separate your concerns in a useful way. In the end, you probably want high-level concepts like an entity (which has behavior, interaction in the physics engine, and a renderable model), and you want to be able to specify its rendering qualities in a data-driven way.

The book I mentioned talks a little bit about the idea of a "Render Packet," which really resonated with me. What I take that to mean is an abstraction layer in which you specify the bare essentials needed to tell the rendering pipeline how to draw something. In OpenGL ES 2, this probably comes down to:

* The shader program (linked vertex / fragment shader)
* Inputs to the shader, like lights and material
* The VBO's (essentially, the "geometry" that you want to render)
* Any transformation matrices (namely, the modelview and projection matrices)

At this level, you've abstracted quite a few API-specific things like the geometry and shaders. Once you've created your shaders and compiled/linked them with the video card, created and defined your VBO's, etc. you can now just specify references to them in order to use them in drawing calls. In my game engine, this abstraction layer basically amounts to my RenderingEngine, which operates on RenderPackets. A RenderPacket is basically these references as well as some other state like blend-mode, depth testing, etc. Essentially, it's everything the video card would need to know to draw a given object correctly.

From here, you can start thinking in a more data-driven context. In my game engine, I have the notion of a RenderableObject. My RenderableObject can be a simple textured quad, an animated sprite, or a full 3-dimensional model. No matter what it is, it specifies enough for my RenderingEngine to know how to assemble a RenderPacket.

I have another abstraction layer that manages the scene. It's basically a scene graph where each node corresponds to a RenderableObject. It's responsible for managing the current modelview matrix, the projection matrix, determining which lights should affect a given object, the current camera, etc. It also does a lot of sorting so that objects can be rendered in the optimal order, as well as ensuring that transparent objects are drawn in the correct order.

Above this, I start getting into very abstract game objects. Each entity in the game has an associated SceneObject, whose renderable qualities are completely data driven. An enemy definition, for example, provides such things as the behavior (controller) of the enemy, its HP, its collision detection bounds, and its renderable definitions.

--

This may not be the answer you're looking for, but I hope it's given you a good perspective on how you can use the OpenGL API to provide a foundation for higher level abstractions. Keep in mind that there are probably many other valid ways in which this is handled.

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


title: Career in Game or in Software/Web

text:
# Question
Title: Career in Game or in Software/Web
I am Currently Working in GameLoft India ..I have also great skills in Web Development and Software Development I had learned J2EE , Sliverlight , Asp. Now I am confused about my career

1)should i continue as a game programmer. 2)Should i try in Adobe, MS , Google. 3)If i continue my career in game field what's the my future.What's thing i need to improve for getting great job in Game field.

Plz reply i am very serious about this

# Answer
Assuming you want to be an Indie game developer :

Let's be straight about one thing, Game Development, Indie if you mean, is hard nut to crack.

If you want to be a game developer having a wide spectrum of skill isn't enough. You need to be persistent and focused about what you do. Test yourself. Make a simple game. For the sake of making things easy, take one existing 2d game you like and replicate it with minor changes. You will get an overall idea of what it takes. Your previous experience will help you to get started.

Regarding your last questions, there is a lot of things you can do to get a job in game industry, in case of big titles. The question is what part of game development are you interested in.

If you are unsure about what to do, and you currently have a job, stick with that and make a game that 'you'd like to make' in your spare time. You will know, if your fit for it.
> 2 votes

---
Tags: game-industry
---


title: Pros and cons of different integrators

text:
# Question
Title: Pros and cons of different integrators
When creating things like physics in games you need an integrator. I've seen Verlet integration mentioned several places as a great alternative to Euler integration. For instance in the famous document by Thomas Jakobsen. However in this article Glenn Fiedler writes:

> Rather than introduce you to the vast array of different integrators that exist, I’m going to cut to the chase and go straight to the best. This integrator is called the Runge Kutta order 4 integrator aka RK4.

So apparently there's no silver bullet. What is the pros and cons of different integrators? Regarding simplicity, speed, accuracy, stability, etc. Which integrators is most suitable for which types of games? When would you use Verlet, RK4 or others? Should you ever use Euler?

# Answer
> 30 votes
Pros and cons of both methods:

RK4 Pros:

1. accuracy (thanks to its better approximation series it yields a 4th order precission)
2. artificial/inherently induced damping (a bit like implicit methods do it) adds stability (whereas a simple Euler step doesn't - it does the opposite actually, introducing ghost energy that builds up and could plunge the system into chaos)

RK4 Cons:

1. computation expense: while not that demanding in comparison to implicit methods or hybrid IMEX methods, RK4 is 4 times more expensive than the explicit Euler since it requires that many more function evaluations. This shows when aiming for the bleeding edge of optimization.
2. still unstable: depending on the types of forces involved, RK4 can be just as unstable as Euler. On average, RK4 is a bit more stable and tends to draw this benefit from its endowed damping "skills".
3. Non-symplectic: numerical damping comes with a cost - you cannot simulate systems where energy/volume/etc. loss shouldn't apply a visible effect over time (e.g. Molecular Dynamics, Potential Field derived forces, variational problems)

Verlet Pros:

1. once or two times the complexity of an Euler step (depending on your Verlet flavour: position or velocity).
2. symplectic: conserves internal energy
3. second order accuracy: many games do not require high precision floating point results, and second order is more than pleasing for the eye in a game scenario (plus: it was used in a non-gaming scenario simulation when it was "discovered", so it's not that bad)

Verlet Cons:

1. stable, but still: probably the best *explicit* method in terms of stability. It tends to win the edge when hard constraints are added to the system, thus allowing for less head-aches when implementing projected constraints in position based dynamics engines. It sets off to infinity if the system is perturbed with large external forces and no damping/friction is added. Even so, there are certain numerically imposed limits to how large the internal (spring) forces can be, but they're higher on average than what RK4 can do
2. lower accuracy: not useful if you want high precission estimations
3. requires, on average, smaller time-steps than RK4 for some simulations (RK4 benefits from both its accuracy and internal damping)

Using one over the other depends on the scenario. If stiffness and large external forces and virtual energies are a problem, then consider other methods having the "implicit" word in their description/title.

---

**Note** some authors/books use the term semi-implicit Euler for an actual explicit Euler integrator called the symplectic Euler method (or Euler Cromer) from which Verlet is actually derived. Verlet is also called by some people the "leapfrog method". Velocity Verlet and the midpoint method are fairly similar since an estimation at a time step of `t + 0.5*dt` is required for a predictor-corrector-like step. IMEX methods (implicit-explicit) are also used to name two similar but not identical approaches: separate the computations into stiff and non-stiff parts and use different integrators on them (the explicit for non-stiff, implicit for stiff) OR solve for the velocity with an implicit update step and update the position in an explicit manner (this is a hybrid semi-implicit method falling on the IMEX class of methods because the stiff parts affect the acceleration computation the most). Implicit methods are more cumbersome and require solving a system of simultaneous non-linear equations for the entire configuration. Implicit methods are used for deformable bodies and usually aren't used for decoupled rigid bodies.

As stated in one of the comments, if you can, do not use Euler. Use either the midpoint method, the semi-implicit Euler or, at the same expense, the position-Verlet. All of them have slightly higher accuracy and sensibly more stability than the explicit Euler integrator.

*Recommended* mini-comparison reading:

http://wiki.vdrift.net/Numerical\_Integration

# Answer
> 3 votes
Euler implementations tend to be very fast, but far less stable than the alternatives. Runge Kutta is slower than Euler, but far more precise and stable.

I'm not very knowledgeable on Verlet integration, so i have no idea how it stacks up against Euler and Runge Kutta.

If you need your simulations to be more exact, or even numerically proof, Runge Kutta is the better of the two.

If you need fast, low cost physics for a simple game, Euler is the better choice.

# Answer
> 2 votes
First and foremost I think you should use Euler until you experiance a direct need to use a more advanced integration scheme. It is fast and easy to implement.

If you experience stability issues such as systems of springs that never come to rest or if your simulation requires a high level of accuracy then start experimenting with the others.

One that I haven't seen mentioned above is the midpoint method which is very easy to implement and only requires one extra integration step.

---
Tags: physics
---


# Question
Title: How to animate the sprite along with action in Cocos2d?
Cocos2d-android - I have an animation which has 5 Frames they are close cropped images. Now I want Sprite to do animation as well as Move in X direction.i.e. I have a player running which gets collided with obstacle and falls down .. Now I want sprite to run animation as well as moveBy in -ve x direction

```
gameOverAnimation =CCSprite.sprite("gmovr00")
gameOverAnimation.setAnchorPoint(0, 0);
gameOverAnimation.setPosition(340.0f, 200.0f);
addChild(gameOverAnimation,10);
CCIntervalAction action1 = CCAnimate.action(mEndAnimation, false);
action1.setDuration(1.0f);
CCIntervalAction delay = CCDelayTime.action(0.68f);
CCMoveBy actionBy = CCMoveBy.action(1.0f, CGPoint.ccp(-340,0));
CCIntervalAction seq1 = CCSpawn.actions(action1,actionBy);
//CCSpawn spawn = CCSpawn.actions(action1, actionBy);
                CCSequence sequence1 = CCSequence.actions(seq1,CCCallFuncN.action(this,"gameOver"));
                gameOverAnimation.runAction(sequence1);

```

Above code makes animation run first then moved in y direction

Thanks for the help.. And can some one explaing me the concept of time with frame Animation or good example ?

# Answer
> 2 votes
```
CCSpriteFrameCache.sharedSpriteFrameCache().addSpriteFrames("grossini_dance.plist");
            grossini = CCSprite.sprite(CCSpriteFrameCache.sharedSpriteFrameCache().spriteFrameByName("grossini_dance_01.png"));
            grossini.setPosition(CGPoint.make(60, fullheight / 3));
            addChild(grossini);
            CCAnimation anim = CCAnimation.animation("", 0.3f);
            for (int i = 2; i <10; i++) {
                anim.addFrame(CCSpriteFrameCache.sharedSpriteFrameCache().spriteFrameByName("grossini_dance_0" + i + ".png"));
            }
            // Creating animation action
            CCAction animaction = CCAnimate.action(2, anim, true);
            grossini.runAction(animaction);

```

Hope it help!!!!!!!!!!

---
Tags: cocos2d
---