# Question
Title: What is a right datatype in C++ for OpenGL scene representation with use of GLSL
I am programming in C++ OpenGl with GLSL. Until now I have been using a data structure that is composed of `std::vector` filled with structures of vertexes and with their parameters (position , normal, color ...) as a global variable for all the code. My question is, as I am using VBOs for drawing - is this a good approach to this problem?

I am asking because I happen to have a lot of memory related trouble with this structure. I am trying to generate a terrain with a lot of vertices - more than 1 million. This seems to work, but as I refill the buffer I get memory related issues (crushes that occur, more or less randomly).

So again the question is, is this a good data structure to use / and look for the faults in my code, or should I change to something else? Or what data structure would be advisable?

# Answer
std::vectors work great.

They have performance at about the same level as a raw c-style array as internally they are basically just a c-style array. There are a few points though.

* Make sure you allocate their size up front when possible either at construction or with std::vector::resize (or even better use reserve). By default vectors grow exponentially since they are a continuous block of memory at each resize they will need to copy every element across.
* The std::vector functions are bounds checked, this might cause slowdowns however you still have access to the c-style methods so you can sacrifice bounds checking for speed. Use vector::\[\] rather than vector::at(x).
* float\* vertices = &vector\[0\]; Will give you the raw C array for use in whatever functions you want.
* C++11 has uniform initialization which makes the syntax for initializing the vectors with fixed data much nicer since you don't have to push\_back everything. But it's no use for reading data in from a file or generating at runtime.

Consider looking at GLM for your base vertices vector type (as in x,y,z vector, not std::vector) type. It's a linear algebra library based on GLSL and is part of the OpenGL SDK (officially recommended support libraries) so it's about as official as you can get. It also has matrix operations which is useful as with modern OpenGL things like glRotate, glTranslate, glPushMatrix, glPopMatrix have all been removed from the core profile. It's very optimized and also has some noise generation functions.
> 3 votes

# Answer
I've had a quick look at VBOs in OpenGL and they seem to be a good way to transfer large amounts of vertices to the Driver. They rely on all the stuff you passed being in one contiguous block of memory.

You're wondering is the STL vector class a good fit? Well it is if you can treat it as single contiguous block of memory for passing to the functions that OpenGL will use for transferring Vertex data between your array and the VBO. So can you do that with a std vector class? According to its documentation:

> vector containers have their elements stored in *contiguous* storage locations, which means that their elements can be accessed not only using iterators but also using offsets on regular pointers to elements.

Thats good news. You can get the memory address of the start of this array ising the techniques shown in the code below. After that fast operations are permitted such as calling memcpy or passing this address to OpenGL.

```
typedef struct {
  long double x, y, z;
} V3;

int main (int argc, const char * argv[])
{
 const int nElems = 100000;
 vector<V3> vec(nElems);
 V3 v;
 V3 *pv = &vec[0];
 for (int i = 0; i < nElems; i++) {
   pv[i] = v;
 }
 pv = &vec[0];
 vector<V3> vec2(nElems);
 V3 *pv2 = &vec[0];
 memcpy(pv2, pv, sizeof(V3)*nElems);
}

```

I would stick with it for the moment. Its not the cause of this problem:

> I get memory related issues(crushes that occur, more or less randomly).

If its crashing at least you can trap it in the debugger.
> 1 votes

# Answer
It is a good enough data structure. For any problems you're having with it, I'd suggest you just run your app in debug mode. If you're doing some byte-fu (copying/modifications) with vector's data, you should check that before everything else. Otherwise, vector has enough assertions placed to let you know where the problem is.
> 0 votes

# Answer
In addition to the notes given in the other answers about use of std::vector, you seem to have a problem in that you're refilling your VBOs every frame.

This is not a good use-case of VBOs (you almost may as well be using old-fashioned client-side arrays, in fact). You need to look at keeping your data static; fill VBOs once-only at load time then use the already-filled VBOs for drawing (if you need to do any animation of data in a vertex then move the animation from the CPU to shader code).

If you want to only draw a subset of data each frame, then you'll get more performance by using a GL\_ELEMENT\_ARRAY\_BUFFER, which can be dynamic, but make sure that you're using a proper buffer-streaming setup for this (see http://www.opengl.org/wiki/Buffer\_Object\_Streaming for further information).

Now, to some this may seem "wasteful" - you're keeping static data in GPU memory that may not be accessed during the current frame. Don't fall into that trap; view a VBO as being like a cache instead; the data may not be needed immediately, but there's a high chance that it will be needed soon, and when that time comes it'll be there, ready and waiting for you.
> 0 votes

---
Tags: opengl, c++, software-engineering, glsl
---


# Question
Title: How to center a game in Flash Projector (like AdamAtomic's CAPSULE)
Adam Atomic's game Capsule is a flash projector. If you press escape, the game goes out of fullscreen and just shows windowed. How do I get my (FLIXEL/AS3) game to show up centered like that?

# Answer
I'm not into Flixel, but don't you simply need this?

```
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = '';

```

stage.align is '' by default.

http://help.adobe.com/en\_US/FlashPlatform/reference/actionscript/3/flash/display/Stage.html#align

http://help.adobe.com/en\_US/FlashPlatform/reference/actionscript/3/flash/display/Stage.html#scaleMode
> 2 votes

---
Tags: flash, actionscript-3
---


# Question
Title: Implement Negascout Algorithm with stack
I'm not familiar with how these stack exchange accounts work so if this is double posting I apologize. I asked the same thing on stackoverflow.

I have added an AI routine to a game I am working on using the Negascout algorithm.

It works great, but when I set a higher maximum depth it can take a few seconds to complete. The problem is it blocks the main thread, and the framework I am using does not have a way to deal with multi-threading properly across platforms.

So I am trying to change this routine from recursively calling itself, to just managing a stack (vector) so that I can progress through the routine at a controlled pace and not lock up the application while the AI is thinking.

I am getting hung up on the second recursive call in the loop. It relies on a returned value from the first call, so I don't know how to add these to a stack.

My Working c++ Recursive Code:

```
MoveScore abNegascout(vector<vector<char> > &board, int ply,
                  int alpha, int beta, char piece) {
if (ply==mMaxPly) {
    return MoveScore(evaluation.evaluateBoard(board, piece, oppPiece));
}

int currentScore;
int bestScore = -INFINITY;
MoveCoord bestMove;
int adaptiveBeta = beta;

vector<MoveCoord> moveList =
    evaluation.genPriorityMoves(board, piece,
                                findValidMove(board, piece, false));

if (moveList.empty()) {
    return MoveScore(bestScore);
}

bestMove = moveList[0];

for(int i=0;i<moveList.size();i++) {
    MoveCoord move = moveList[i];

    vector<vector<char> > newBoard;
    newBoard.insert( newBoard.end(), board.begin(), board.end() );
    effectMove(newBoard, piece, move.getRow(), move.getCol());

    // First Call ******
    MoveScore current = abNegascout(newBoard, ply+1, -adaptiveBeta,
                                    -max(alpha,bestScore), oppPiece);

    currentScore = - current.getScore();

    if (currentScore>bestScore){
        if (adaptiveBeta == beta || ply>=(mMaxPly-2)){
            bestScore = currentScore;
            bestMove = move;
        }else {
            // Second Call ******
            current = abNegascout(newBoard, ply+1, -beta,
                                  -currentScore, oppPiece);
            bestScore = - current.getScore();
            bestMove = move;
        }

        if(bestScore>=beta){
            return MoveScore(bestMove,bestScore);
        }
        adaptiveBeta = max(alpha, bestScore) + 1;
    }
}
return MoveScore(bestMove,bestScore);
}

```

If someone can please help by explaining how to get this to work with a simple stack. Example code would be much appreciated. While c++ would be perfect, any language that demonstrates how would be great.

Thank You.

# Answer
> 1 votes
So I finally managed to convert my AI routine using this fantastic article which explains everything in detail. The only thing that wasn't covered and which I had trouble with was how to deal with the fact that my nested recursive statements were in a loop that was created on each recursive step. I got around that by breaking each stage of code into a separate method and re-assigning the stage number to 1, in this case, which would iterate to the next item in the list.

It works great. Through testing it appears to generate the identical results that I had before. What I've done is call the main method (abNegascoutwithStack) on each tick of the game loop to processes a part of the stack until the stack is empty or until n milleseconds have passed and then wait for the next game tick.

I have not noticed it running any slower and the benefit of being able to completely control the routine is great. A truly cross-platform solution that does not require multi-threading.

This was a lot of work for me so I hope that I can save someone else the time/energy/headaches by sharing my code here. It's not perfect but it works. I have only included the parts of code relevant to Negascout, not my entire game.

The 'stack' struct

```
struct SnapShotStruct {
   vector<vector<char> > board;
   int ply;
   int alpha;
   int beta;
   char piece;

   char oppPiece;
   int currentScore;
   int bestScore;
   MoveCoord bestMove;
   int adaptiveBeta;
   vector<MoveCoord> moveList;
   int moveListIndex;
   MoveCoord move;
   vector<vector<char> > newBoard;
   MoveScore current;
   int stackID;
   int stage;
};

int uniqueStackID;
float lastAiRun;
SnapShotStruct currentSnapshot;

stack<SnapShotStruct> snapshotStack;
MoveScore retVal;

```

Assign Initial Values to the first item in the stack:

```
currentSnapshot.board = board;
currentSnapshot.ply = 0;
currentSnapshot.alpha = -INFINITY;
currentSnapshot.beta = INFINITY;
currentSnapshot.piece = piece;
currentSnapshot.stage=0;

snapshotStack.push(currentSnapshot);
uniqueStackID = 0;

```

Then from your gameloop make calls as needed

abNegascoutwithStack:

```
void abNegascoutwithStack(){
currentSnapshot=snapshotStack.top();
snapshotStack.pop();

switch(currentSnapshot.stage) {
case 0:
    if (abNegascout0()) {
        return;
    }
case 1:
    if (abNegascout1()) {
        return;
    }
case 2:
    if (abNegascout2()) {
        return;
    }
case 3:
    if (abNegascout3()) {
        return;
    }
case 4:
    if (abNegascout4()) {
        return;
    }
break;
}
}

```

abNegascout0:

```
bool abNegascout0() {
currentSnapshot.stackID = uniqueStackID;
uniqueStackID++;

currentSnapshot.oppPiece = (currentSnapshot.piece == sBLACK_PIECE) ? sWHITE_PIECE : sBLACK_PIECE;

if (currentSnapshot.ply==mMaxPly){
    retVal = MoveScore(evaluation.evaluateBoard(currentSnapshot.board, currentSnapshot.piece, currentSnapshot.oppPiece));
    return true;
}

currentSnapshot.currentScore = 0;
currentSnapshot.bestScore = -INFINITY;
currentSnapshot.adaptiveBeta = currentSnapshot.beta;

currentSnapshot.moveListIndex = -1;
currentSnapshot.moveList = evaluation.genPriorityMoves(currentSnapshot.board, currentSnapshot.piece, findValidMove(currentSnapshot.board, currentSnapshot.piece, false));

if (currentSnapshot.moveList.empty()) {
    retVal = MoveScore(currentSnapshot.bestScore);
    return true;
}

currentSnapshot.bestMove = currentSnapshot.moveList[0];
return false;
}

```

abNegascout1:

```
bool abNegascout1() {
currentSnapshot.moveListIndex++;
if (currentSnapshot.moveListIndex < currentSnapshot.moveList.size()) {
    currentSnapshot.move = currentSnapshot.moveList[currentSnapshot.moveListIndex];
    currentSnapshot.newBoard.clear();
    currentSnapshot.newBoard.insert( currentSnapshot.newBoard.end(), currentSnapshot.board.begin(), currentSnapshot.board.end() );

    effectMove(currentSnapshot.newBoard, currentSnapshot.piece, currentSnapshot.move.getRow(), currentSnapshot.move.getCol());

    currentSnapshot.stage = 2;
    snapshotStack.push(currentSnapshot);

    SnapShotStruct newSnapshot;
    newSnapshot.board = currentSnapshot.newBoard;
    newSnapshot.ply = currentSnapshot.ply+1;
    newSnapshot.alpha = -currentSnapshot.adaptiveBeta;
    newSnapshot.beta = - max(currentSnapshot.alpha,currentSnapshot.bestScore);
    newSnapshot.piece = currentSnapshot.oppPiece;

    newSnapshot.stage=0;
    snapshotStack.push(newSnapshot);
    return true;
}
retVal = MoveScore(currentSnapshot.bestMove,currentSnapshot.bestScore);
return true;
}

```

abNegascout2:

```
bool abNegascout2() {
currentSnapshot.current = retVal;
currentSnapshot.currentScore = - currentSnapshot.current.getScore();

if (currentSnapshot.currentScore > currentSnapshot.bestScore){
    if (currentSnapshot.adaptiveBeta == currentSnapshot.beta || currentSnapshot.ply>=(mMaxPly-2)){
        currentSnapshot.bestScore = currentSnapshot.currentScore;
        currentSnapshot.bestMove = currentSnapshot.move;
        return false;
    } else {
        currentSnapshot.stage = 3;
        snapshotStack.push(currentSnapshot);

        SnapShotStruct newSnapshot;
        newSnapshot.board = currentSnapshot.newBoard;
        newSnapshot.ply = currentSnapshot.ply+1;
        newSnapshot.alpha = -currentSnapshot.beta;
        newSnapshot.beta = -currentSnapshot.currentScore;
        newSnapshot.piece = currentSnapshot.oppPiece;

        newSnapshot.stage=0;
        snapshotStack.push(newSnapshot);
        return true;
    }
}

currentSnapshot.stage = 1;
snapshotStack.push(currentSnapshot);
return true;
}

```

abNegascout3:

```
bool abNegascout3() {
if (currentSnapshot.stage != 3) {
    return false;
}
currentSnapshot.current = retVal;
currentSnapshot.bestScore = - currentSnapshot.current.getScore();
currentSnapshot.bestMove = currentSnapshot.move;

return false;
}

```

abNegascout4:

```
bool abNegascout4() {
if(currentSnapshot.bestScore>=currentSnapshot.beta){
    retVal = MoveScore(currentSnapshot.bestMove,currentSnapshot.bestScore);
    return true;
}
currentSnapshot.adaptiveBeta = max(currentSnapshot.alpha, currentSnapshot.bestScore) + 1;

currentSnapshot.stage = 1;
snapshotStack.push(currentSnapshot);
return true;
}

```

---
Tags: c++, recursion
---


# Question
Title: What exactly does an installer do and why might I need one?
this is probably the noob-question of the day:

So I've written this game.

Now there's the .exe file that does the work, a folder with my beautiful, beautiful assets and a bunch of .dll files and other stuff that I probably shouldn't touch. To run the game, I copy the whole lot to the desired computer, double-click the .exe file and start shooting some dudes. Yay!

But what exactly is the difference between that and using an installer? What else does an installer do besides copying files and looking more professional than a .zip-file? Is there generally a lot of patching/configuring involved when trying to make a game run on a different computer? I tested my game on all windows computers I could get my greedy fingers on and it works great.

# Answer
The installer is typically there to make things easier for the end user. It does some combination of the following:

* Unzipping
* Creation of directories
* Installation of required runtimes (redistributable like: .Net, Visual C++, Direct x)
* Registration with the OS (for later clean uninstall)
* Display beautiful, beautiful screenshots to prepare the player for your game while it works.
* Offering the user the chance to register their game
* Downloading updates for the assets or patches for the game
* Add icons to the start menu or the desktop
* Set correct permissions for various game directories (temp folder, save directory, etc.)
* **Just install it already**, allow the user to mindlessly click next and get to playing the game!
> 36 votes

# Answer
An installer **abstracts the process of deploying complex pieces of software infrastructure**, which is usually **contained within an archive, through a convenient, self-sufficient user interface**.

This UI can be graphical or based on text which is output on a command-line such as the unix shell (e.g. bash). In case of graphical installers, most often a so called installation-bootstrapper is used, in the latter case, installation scripts which can be bash-scripts, Microsoft batch scripts, or other any scripting language which runs on a command line.

In the **simplest case** an application is simply **an executable file,** with the operating system knowing what to do with the file in order to run it. The application file may reside in a folder with subfolders and other auxiliary files, **packed into one archive**. In this case no installer may be needed.

**For complex software**, entire software platforms and **tight integration with the underlying operating system infrastructure** may be desirable, for instance to enforce the copyright of a software product.

Many installers on Windows provide an `/e` or `/extract` flag. e.g. `setup.exe /e` to allow extraction of the archive's contents without the installer running its installation script. I recently needed to do just that.

**Towards portability**

Installers have almost become a norm for delivering professional software, no matter how simple the underlying software assets. With an increasing number of computer savvy users and the desire to migrate ones applications from one desktop to the next, **portable software**, often delivered in a simple archive, is becoming increasingly popular.

( *I don't know how much time in total I have spent on installers, but it is definitely on the order of days.* )

**Tasks the installer may handle, are:**

* unpacking (often using exotic, high compression archivers)
* ensuring system hardware requirements
* ensuring sufficient hard-disk space
* ensuring software platform runtime requirements (e.g. 'redistributables')
* checking for newer software updates
* downloading the software from a remote repository
* creating and/or updating program files and folders
* create configuration files, registry entries or environment variables
* install sofware drivers, mount or unmount devices
* increase accessibility for everyday users, by explaining installation steps, creating links, shortcuts
* promote the own sofware through bookmarks, etc...
* create incentive for the user to actually startup the software, by presenting the keypoints of the software during the installation, slide by slide
* create additional revenue, through software-bundling
* configure kernel-modules and automatically running components (e.g. daemons, windows-services)
* automatic patching of the sofware
* setting folder, file and user permissions
* creating GUIDs to couple the software to a specific installation-instance and for instance, prevent portability

... If you can think of other points, let me know and I will incorporate them.
> 4 votes

---
Tags: installer
---


title: sprite animation in openGL

text:
# Question
Title: sprite animation in openGL
I am facing problems on implementing sprite animation in openGL ES. I've googled it and the only thing i am getting is the Tutorial implementing via Canvas.

I know the way but I am having problems in implementing it.

What I need : A sprite animation on collision detection.

What I did : Collision Detection function working properly.

PS : Everything is working fine but i want to implement the animation in OPENGL ONLY. Canvas won't work in my case.

------------------------ EDIT-----------------------

I now have a sprite sheet, say the one below having some certain co-ordinates, but from where will be the (u,v) co-ordinates start? Should I consider my u,v co-ordinates from (0,0) or from (0,5) and in which pattern should i store them in my list..? ----\> From Left to right OR ----\> from top to bottom

Do i need to have a 2D array in my sprites class? here is the image for a better understanding.

I am assuming that I have a NxN sprite sheet, where N = 3,4,5,6,....and so on.

.

.

```
class FragileSquare{

FloatBuffer fVertexBuffer, mTextureBuffer;

ByteBuffer mColorBuff;

ByteBuffer mIndexBuff;

int[] textures = new int[1];

public boolean beingHitFromBall = false;

int numberSprites = 49;

int columnInt = 7;      //number of columns as int

float columnFloat = 7.0f; //number of columns as float

float rowFloat = 7.0f;

public FragileSquare() {
    // TODO Auto-generated constructor stub

    float vertices [] = {-1.0f,1.0f,            //byte index 0
                         1.0f, 1.0f,            //byte index 1
                                    //byte index 2
                         -1.0f, -1.0f,
                         1.0f,-1.0f};           //byte index 3

    float textureCoord[] = {
                            0.0f,0.0f,
                            0.142f,0.0f,
                            0.0f,0.142f,
                            0.142f,0.142f

    };

    byte indices[] = {0, 1, 2,
            1, 2, 3 };

    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4*2 * 4); // 4 vertices, 2 co-ordinates(x,y) 4 for converting in float
    byteBuffer.order(ByteOrder.nativeOrder());
    fVertexBuffer = byteBuffer.asFloatBuffer();
    fVertexBuffer.put(vertices);
    fVertexBuffer.position(0);

    ByteBuffer byteBuffer2 = ByteBuffer.allocateDirect(textureCoord.length * 4);
    byteBuffer2.order(ByteOrder.nativeOrder());
    mTextureBuffer =  byteBuffer2.asFloatBuffer();
    mTextureBuffer.put(textureCoord);
    mTextureBuffer.position(0);

}

public void draw(GL10 gl){

    gl.glFrontFace(GL11.GL_CW);

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(1,GL10.GL_FLOAT, 0, fVertexBuffer);
    gl.glEnable(GL10.GL_TEXTURE_2D);
    int idx = (int) ((System.currentTimeMillis()%(200*4))/200);
    gl.glMatrixMode(GL10.GL_TEXTURE);
    gl.glTranslatef((idx%columnInt)/columnFloat, (idx/columnInt)/rowFloat, 0);
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glEnable(GL10.GL_BLEND);
    gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); //4
    gl.glTexCoordPointer(2, GL10.GL_FLOAT,0, mTextureBuffer); //5
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4); //7
    gl.glFrontFace(GL11.GL_CCW);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
    gl.glMatrixMode(GL10.GL_TEXTURE);
    gl.glLoadIdentity();
    gl.glMatrixMode(GL10.GL_MODELVIEW);
}

public void loadFragileTexture(GL10 gl, Context context, int resource)
{
    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resource);
    gl.glGenTextures(1, textures, 0);
    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);
    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
    bitmap.recycle();
}

```

}

# Answer
> 6 votes
This is a code snippet I'm using in my Android application.

```
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glMatrixMode(GL10.GL_TEXTURE);    //edit the texture matrix
gl.glTranslatef(u, v, 0);            //translate the uv space (you can also rotate, scale, ...)
gl.glMatrixMode(GL10.GL_MODELVIEW);  //go back to the modelview matrix
gl.glBindTexture(GL10.GL_TEXTURE_2D, getTexture());
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);           //map the texture on the triangles
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, getTextureBuffer()); //load texture coordinates

```

The trick here is to use glMatrixMode followed by glTranslatef. That will allow you to translate the uv space.

uv coordinates range from (0,0) to (1,1)

Let's suppose you have a squared texture with 4 frames and you want to texturize a quad. I will use the following coordinates to define frames in uv space (the choice is up to you)

1st (0, 0) (0.5, 0.5)

2nd (0.5, 0) (1, 0.5)

3rd (0, 0.5) (0.5, 1)

4th (0.5, 0.5) (1, 1)

With glTexCoordPointer you should map the 1st frame on your quad then when you want to show the 2nd frame you call glTranslatef(0.5, 0, 0), glTranslatef(0, 0.5, 0) for the 3rd and glTranslatef(0.5, 0.5, 0) for the 4th.

The code above is tested and work very well, I hope the example is clear enough.

---

EDIT:

at the end of your draw function you should reset your texture matrix whit this code.

```
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glMatrixMode(GL10.GL_TEXTURE);
gl.glLoadIdentity();
gl.glMatrixMode(GL10.GL_MODELVIEW);

```

---

ok, let's take 5 rows and 4 columns as an example. There are max 20 sprites in your spriteset so use int idx = (int)((System.currentTimeMillis()%200\*number\_of\_sprites)))/200);

idx now go from 0 to number\_of\_sprites-1 (can be \< 20 if you have for example 5 rows, 4 columns but only 18 sprite) changing it's value every 200ms. Assuming you have your sprite from left to right and from top to bottom than you can find your frame coordinate in uv space doing this.

```
int c = 4;      //number of columns as int
float cf = 4.f; //number of columns as float
float rf = 5.f; //number of rows as float
gl.glTranslatef((idx%c)/cf, (idx/c)/rf, 0);

```

when you do idx%c you find your column index, the results is always between 0 and c-1

idx%c is an integer, you need to scale it to a value between 0.0 and 1.0 so you divide by cf, cf is a float so there is an implicit cast here

idx/c is the same thing but for rows, idx and c are both integer so the result is still integer, and it's the row index, dividing by rf you get a value between 0.0 and 1.0

# Answer
> 1 votes
My suggestion: Create texture containing all of your frames of your animation (side by side). Change the texture coordinates according to the frame you want to display.

# Answer
> 1 votes
You need to use something called a **spritesheet**.

A spritesheet is just a single image with all the different "frames" that show the poses the character can take. You select which "frame" of the sprite sheet to display either based on time (as for an explosion animation) or on player input (such as facing left, right, or drawing a gun)

The *easiest* way to do something like this is to have all related sprites be the same size (same width and height), and so getting the (u) coordinate of the 4th sprite from the left is just `(sprite_width*4.0 / sprite_sheet_width)`.

If you're trying to optimize and be space efficient, you can use a tool like TexturePacker to pack your sprites onto a single sheet. TexturePacker also emits json or xml data that describes the xy locations of each of the sprites you load in.

# Answer
> 1 votes
You can use I\_COLLIDE with OpenGL.

Make each entity in the world a box, then check if each of the axises of the box are colliding with other entities.

With large amounts of entities to test for collisions you may want to check into an octree. You would simple divide the world into sectors, then only check for collision between objects in the same sectors.

Also utilize Bullet dynamics engine which is an open source collision detection and physics engine.

---
Tags: android, sprites
---


title: 3D space game development

text:
# Question
Title: 3D space game development
I want to develop a 3D game (sci-fi type with spaceships) which can be played on multiplayer mode and by multiplayer i mean around 10 players for start as it will be a personal testing project and mostly educational. I have been searching for some days about the available languages and engines but i am kinda confused. Since i have been learning Java for my 1st year in I.T university and i have pretty good understanding i thought i would go with the Java language and develop that game on an applet so it could be played on a browser. After going through an applet game tutorial i understood how graphics work on an applet.

So.. 1st question: Could an applet carry the burden of a 3D game especially on multiplayer? My thinking: It's a space game so the graphics should not be such a big problem since it wont be that crowded with entities apart from ships, planets and some effects.

If the java applet is not the way for my project i would't mind "developing it on desktop"(i mean not making it a browser game). 2nd question: Should i use Unity engine for my purpose(space game)? If not name other language/engine combo.

# Answer
> 2 votes
To answer your question, yes, Java can carry the burden of a 3D game: http://en.wikipedia.org/wiki/RuneScape

Java is not the only language you can use for a browser game. You mentioned Unity too, but there's also Flash (Actionscript) that now supports hardware rendering with stage3D, and has a nice library Away3D. You won't code your server in Actionscript or Unity, though.

I'd suggest learning one thing at a time:

* a complex 2D game, where you will learn the language, and MVC
* modifying a ready game to have multiplayer functionality, where you will learn server language, as well as many connection issues like client-server desynchronization
* Adding another dimension to the game.
* Adding MMO functionality, logging in, storing data in database, making sever scalable and secure.

I'll add next point in 10 years, when you finish those :)

---
Tags: 3d, mmo
---


# Question
Title: Novice prototyping a massive multiplayer webpage based gaming system
I'm trying to build a website based game in which various pages of the site act as different areas of the game. I am wondering what you would recommended as a design structure. Which languages would be best if building what will hopefully becomes a massive system able to scale to massive amounts of users.

I am wondering if and how various elements from differing languages could be meshed to interact with each other. For example could I use html5, javascript, and PHP? What about asp.net how might that factor in? I'm a newbie programmer but I've been working on this idea for years and I want to build it to reality. Your comments and suggestions are appreciated.

P.S.: The game is not all graphics and animation (though flash like appearance and some animation would be nice). What I am thinking of is essentially a heavily gamified system of forms. And LOTS of data in many different categories cross referencing each-other. I'm not sure how to go about structuring the collection of data. Also while I know javascript can be used to process some functions, I'm wondering what sort of base system I would need to handle the server side processing of what I am expecting to be some pretty significant algorithm processing. That is to say I expect to have many many many functions and I'm not sure how to mange this using javascript. I feel like they would be forgotten, mixed up, disorganizes as they essentially only exist where they are coded. I guess I need to learn something of libraries?

OK, Thank you! Is enough from me for now.

# Answer
> 2 votes
> could I use html5, javascript, and PHP?

Yes you can and you definitely will need to do so. While html will mostly define the look and feel of your page you will need php (which run server side BEFORE the page loads http://en.wikipedia.org/wiki/Server-side\_scripting) to get your forms filled up and use javascript to modify the page on run time. Maybe you want to dive down in ASP.net, which allows you to script your logic in an .net language and has proven itself to me as much more powerful (personal opinion).

> And LOTS of data in many different categories cross referencing each-other

For your data you may want to check out SQL. It stores data in a database and with its queries you can access, combine and alter the data really quick. http://www.mysql.com/ It has interfaces for nearly every other language so you can use it from php, javascript and asp.net.

> I guess I need to learn something of libraries?

Libraries are definitely a good starting point. Maybe you want to look for an "all-in-one" solution, which will keep you a bit limited, but will keep you also away from all the deep programming logic.

Here are some quick results:

Stackoverflow question regarding php game engines

Very good list of JavaScript game engines

Regards floAr

# Answer
> 1 votes
Even if you aren't a seasoned developer, I feel I can suggest you to think about HTML5-NodeJS-NOSQL(mongodb or couchdb) triptych. I told you this because the era of centralized server side computing is slowly fading in favour of a different way to think in a scalable way.

Today a simple multiplayer game can be done in a single html page that does not refresh but its state is updated using async communications and DOM changes; libraries such as Socket.io would let you to push events into your clients when other clients perform some action in a Near-realtime fashion.

This is the architecture that I would use right now if I were asked to do such a thing:

**Client**

Modelling the game internals using Backbone.js: This library implements the famous Model View Controller pattern, so Models are objects that hold the status of your game parts and are able to send *Events* when they changes.

Using some library such as Crafty.js or similary to provide some higher level of abstraction over common task related to game development.

**Server**

Developing server that is a thin wrapper over a Document Based Database. It basically serves the static pages that contain the client-side logic; orchestrates the communication with clients (see later); compiles documents containing chunks of information related to state that is needed to be persistent and saves them into a Document Based Database.

**Client/Server communications**

The clients send async messages using Socket.io when they needs to notify the server about their internal state updates; they ask for resources asynchronously (images, animations, sound, interface chunks ect).

You can write controllers that observe the state of models(by registering callbacks on model events) and react by sending messages to the server when needed. Conversely models can register callback to socket.io incoming messages so that they will simply update its state accordingly to the content of the received message.

When the server receives Socket.io messages from a client and send it back to other clients in order to update their state if this is needed; when persistence is needed the information can be saved in JSON document to save into a couchdb database (for example). For example, if you want to save the state of the player, the server can simply update de player status json document on the databse and retrive it when the player logs back in.

If tomorrow you want to add some features to your player profile - i.e. add information to store within its database record - you do not need to alter tables as you did in relational database, but simply store new information in the updated document; old version of your software may simply ignore the new infos while other can take advatage from them.

Obviously the server has to validate the communications since the game logic resides into the client. In this architecture, the messages are the outcome of the game progession as computed into the clients, so the server need to check and certificate the validity of a message before send the conseguent messages to related client.

# Answer
> 1 votes
The first step is to flesh out the actual game idea. Only then shop around for technical *how*.

You have a story? Can you make a flow for it? Pay particular attention to the multi-player aspect; can players be in the same 'room' as other players, how will their actions be reflected in the views of other players, and so on?

Typically you end up with a whole load of 'player' objects in a server and having to use ajax/websockets to update players. When you're ready to start coding, look for the various 'chat' examples in server-side scripting languages.

---
Tags: java, software-engineering, html5, php
---


# Question
Title: Better way to do AI Behavior in AS3/Flixel
I'm making a game in Flixel and I need to program an NPC. It's rapidly turning more complex than I expected. I was wondering if there are any best practices, tutorials or examples that you can refer me to, to see how this is done.

I can probably hack it together, which is what I always do, but it would be nice if I can make it maintanable and can add stuff later on.

Here's screenshot to give you an idea: The butler will be an NPC that will follow you, or guide you, and talk to you the whole time.

**EDIT:** More specifically: What I have now is a long list of IF statements in the update loop of the butler (about 8 different cases), and all I have covered is his walking behavior. I want him to comment on things and sometimes switch his main behavior to be more aggresive or distant,... Is there any way to keep track of this, or is complex code with many many nested if statements the way to go?

# Answer
From your description it sounds like you need some kind of state machine, maybe switchable for different rooms/zones to keep things maintainable. Take a look also at Behavior Trees: http://twvideo01.ubm-us.net/o1/vault/gdc10/slides/ChampandardDaweHernandezCerpa\_BehaviorTrees.pdf
> 2 votes

---
Tags: ai, npc
---


title: terminology: a position and a facing

text:
# Question
Title: terminology: a position and a facing
my units have a function that returns a position (vec3) and a facing (quaternion) for any point in time.

A position and direction is perhaps called a *ray* or, in some contexts, a *line segment*; however, neither of these sounds appropriate in this context and neither normally has a quaternion...

What better name should a compound position and facing be called?

# Answer
> 6 votes
Well, the Robotics people call it pose (position+orientation).

# Answer
> 3 votes
It's usually called a Transform (sometimes shortened to xForm). It also usually includes scale.

---
Tags: terminology
---


title: RagDoll in AndEngine

text:
# Question
Title: RagDoll in AndEngine
I want to create a RagDoll body in andEngine which can run and jump over different jumpObjects. Can any one give a nice tutorial on how to create RagDoll body and how to move it, like jump and running.

Thanks in Advance.

# Answer
I think you mis concept all the thing. For developing contra like character you have to create a single body either box or circle that does not matter. For providing jump you have to give impulse to that single body. And body contains the sequence of sprite to make all the effect like walking, jumping etc. If does not require then you do not need to create a joints between multiple bodies.
> 1 votes

---
Tags: android, box2d, andengine
---


# Question
Title: Updating games for iOS 6 and new iPhone/iPod Touch
Say I have a game that runs full-screen on iPhone 4S and older devices. The balance of the game is just right for the 480 x 320 screen and associated aspect ratio. Now I want to update my game to run full-screen on the new iPhone/iPod Touch where the aspect ratio of the screen is different.

It seems like this can be challenging for some games in terms of maintaining the "balance". For example if the extra screen space was just tacked onto the right side of Jet Pack Joyride the balance would be thrown off since the user now has more time to see and react to obstacles.

Also it could be challenging in terms of code maintenance. Perhaps Jet Pack Joyride would slightly increase the speed of approaching obstacles when the game is played on newer devices. However this quickly becomes messy when extra conditional statements are added all over the code. One solution is to have some parameters that are set in once place at start-up depending on the device type.

**What are some strategies for updating iOS games to run on the new iPhone and iPod Touch?**

**Edit - more info:** I wonder what happens with a game like Plants vs Zombies? There's quite a bit of artwork that's probably sized to the 320x480 screen. Perhaps the lawn background's width can be increased while the size of the zombies and the row heights stay the same.

# Answer
I found the solution for this from the Cocos2d-x forums. The following code is needed in the didFinishLaunching method:

```
  // Set RootViewController to window
  NSString *reqSysVer = @"6.0";
  NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
  if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending) {
    [window setRootViewController:viewController]; //iOS 6
  } else {
    [window addSubview: viewController.view]; //iOS 5 or less
  }

```

An example of the full method:

```
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  // Override point for customization after application launch.
  // Add the view controller's view to the window and display.
  window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
  EAGLView *__glView = [EAGLView viewWithFrame: [window bounds]
                                 pixelFormat: kEAGLColorFormatRGBA8
                                 depthFormat: GL_DEPTH_COMPONENT16
                          preserveBackbuffer: NO
                                  sharegroup: nil
                               multiSampling: NO
                             numberOfSamples: 0 ];
  // Use RootViewController manage EAGLView
  viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
  viewController.wantsFullScreenLayout = YES;
  viewController.view = __glView;
  // Set RootViewController to window
  NSString *reqSysVer = @"6.0";
  NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
  if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending) {
    [window setRootViewController:viewController]; //iOS 6
  } else {
    [window addSubview: viewController.view]; //iOS 5 or less
  }
    [window makeKeyAndVisible];
    __glView.multipleTouchEnabled = YES;
    [[UIApplication sharedApplication] setStatusBarHidden: YES];
    cocos2d::CCApplication::sharedApplication()->run();
    return YES;
}

```

and possibly this code in your RootViewController:

```
-(NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscape;
}
- (BOOL)shouldAutorotate {
    return YES;
}

```
> 2 votes

---
Tags: iphone, ios, aspect-ratio
---


title: Load all content from folder

text:
# Question
Title: Load all content from folder
I want to ask, is there way to load in xna all content from folder ?
For example in my content I have:
Images/hero
Images/car
Images/tree
I want to make something like this

```
Dictionary<string,Model> models = new ...

foreach(string name in content.getNames("Images"))
{
    models[name] = content.load<Model>("Images\\" + name);
}

```

# Answer
> 3 votes
There's a great MSDN page about a useful directory access method and someone's asked a similar question on StackOverflow.

Basically, find the files that are in that directory, initialise an array of that size and then iterate through those files, loading in the resources.

# Answer
> 3 votes
http://xbox.create.msdn.com/en-US/sample/contentmanifestextensions

It's a tutorial about loading content at runtime. It shows how to generate a list automatically by using the content pipeline.

# Answer
> 0 votes
You can easily list all the files inside a folder and then load them one by one. By default all content files are stored in a folder right beside your main application so you just need to check for the contents of that direction. You can also use a recursive function if you want to load all files from all the directories. here is a little sample:

```
string[] files = Directory.GetFiles("content\\Images");
for (int i = 0; i < files.Count(); i++)
{
    textures.Add(Content.load<Texture2D>(files[i].Remove(0,"Content\\".Length)));
}

```

notice that when you are asking content system to load a texture, you should drop "content" folder from file name.

---
Tags: xna, xna-4.0
---


# Question
Title: How can I create a VBO of a type determined at runtime?
I've written a Vbo template class to work with OpenGL.

I'd like to set the type from a config file at runtime. For example:

```
<vbo type="bump_vt" ... />

Vbo* pVbo = new Vbo(bump_vt, ...);

```

Is there some way I can do this without a large `if-else` block such as:

```
if( sType.compareTo("bump_vt") == 0 )
    Vbo* pVbo = new Vbo(bump_vt, ...);
else if
    ...

```

I'm writing for multiple platforms in C++.

# Answer
Yes, this can be done for your case using any kind of associative mapping data structure, such as C++'s standard `std::map` container. At the most general level, you'll be building a implementation of a design concept known as a factory.

The general concept, as I describe in this similar answer, is to use an associative mapping of key values to either the desired type of data or a function that will produce the desired type of data (via a function pointer, or similar).

In you case it looks like you have constants for the VBO types (such as `bump_vt`). In other words it looks like you have:

```
enum BufferType {
  bump_vt,
  whatever_vt,
  another_vt,
};

```

Since you don't have any particularly complex types or inheritance, as far as I can tell, you can implement this factory in a rather straightforward fashion using a simple wrapper around C++'s built-in `std::map` class:

```
struct VboFactory {
  void AddType (const std::string & key, BufferType type) {
    m_types[key] = type;
  }

  Vbo * CreateVbo (const std::string & key) {
    return new Vbo(m_types[key]);
  }

private:
  std::map<std::string, BufferType> m_types;
};

```

To make use of this class, you instantiate an instance of `VboFactory` somewhere and register the known set of buffer types with it; this is typically done early in the initialization process for your rendering system (the factory should probably also be a member variable of some managing subsystem, such as the renderer itself, instead of a local variable as my sample code here implies):

```
VboFactory factory;
factory.AddType("bump_vt", bump_vt);
factory.AddType("whatever_vt", whatever_vt);
// ...etc...

```

Then, you can read the VBO type from your data file as a string and send that to the factory for creation of the VBO itself:

```
std::string type = ReadVboTypeFromFile();
Vbo * vbo = factory.CreateVbo(type);

```

In a more complex world, of course, you could replace the mapping from string to buffer type constant with a mapping from string to function pointer and register function pointers with the factory instead, allowing more involved customization of the VBO construction process.

For example, your original question indicates your VBO class is a template, and template parameters (even non-type parameters, as you appear to be using) must be specified at compile time, so my simple example isn't entirely sufficient. You also have to deal with the issue of the return type of the function, and so you'll need a common base class for all VBO template classes:

```
struct IVbo {
  // ...
};

template<BufferType T>
struct Vbo : IVbo {
  // ...
};

typedef IVbo * (*VboCreationFunction)();

struct VboFactory {
  void AddType (const std::string & key, VboCreationFunction creationFunction) {
    m_types[key] = creationFunction;
  }

  IVbo * CreateVbo (const std::string & key) {
    return m_types[key]();
  }
}

// ...elsewhere..
IVbo * CreateBumpVbo() {
  return new Vbo<bump_vt>();
}

// ...elsewhere...
VboFactory factory;
factory.AddType("bump_vt", CreateBumpVbo);

std::string vboType = ReadVboTypeFromFile();
IVbo * vbo = factory.CreateVbo(type);

```

That's the gist, at least. Obviously there will be other things you'll want to handle or define yourself, such as the interface for VBOs themselves (what is and isn't in the templated version versus the base class) and error handling for the factory itself.

I should also note that this kind of approach is highly-generalized -- possibly too generalized to be the most ideal solution for your problem. If you actually have a very small VBO type set and very simple construction semantics for them, there isn't anything wrong with an `if-else` chain. The primarily advantage of abstracting this out into a factory comes from the ability to extend the set of created types from client code without having to modify the library code, which is a huge benefit on larger code bases... but may not be applicable to you.
> 5 votes

# Answer
Rather than hard-coding it to specific vertex types I'd be inclined to make things a little more general. After all, VBO creation is not hard-wired to any vertex type, is it? All you need is to provide a total buffer size (in bytes) in that initial glBufferData call, and using vertex types will limit you to those you've pre-defined: if you ever need to add another you'll need to go through your code and fix things up.

So, let's look at how we can create this. An obvious candidate is the parameters you'll be passing to your glVertexAttribPointer calls - these, and not VBO creation, are what really define the vertex type, so building something around them seems a more sensible approach.

So in your config you'll define a vertex type, define the number of attribs it has, and for each attrib you define it's GL type (GL\_FLOAT, GL\_UNSIGNED\_BYTE, etc) and the number of components it uses (1, 2, 3 or 4). Then when time comes to create the VBO you walk through this list adding things up as you go until you get the vertex size; multiply that by the number of verts you want in the buffer, and hey presto - out comes the buffer size.

As a bonus this kind of setup can also be used for auto-generating the glVertexAttribPointer calls needed, so you get a really nice flexible and extensible setup with a low level of interdependency.
> 2 votes

# Answer
What's wrong with if-else blocks? If you don't have dynamic VBO types (the post didn't suggest anything like it), it's essentially the best solution. Don't fall in temptation to overdesign the solution - if it works, it's good. Everything else will just equal more code (more work / time spent) with the same results - and I don't think that is what you want.
> 1 votes

---
Tags: c++
---


title: Which version of OpenGL for Android?

text:
# Question
Title: Which version of OpenGL for Android?
I've been trying to learn OpenGL ES 2.0 to create a simple 2D game. I bought a book on android development, but after seeing that the author uses his own SDK that implements OpenGL ES 1.0 I decided to just use online tutorials. I've been so lost trying to find out what to use. The Matrices and shaders of 2.0 confuse me and I can't find any tutorial that just explains how to texture map a simple 2D image. Basically:

* OpenGL ES 1.x or 2.0 for simple 2D with little OpenGL experience
* If 2.0 Any good tutorials for 2.0, I've found so many for 1.0

# Answer
> 5 votes
I'd rather say, First clear your concepts with OpenGL ES 1.x then go for OpenGL ES 2.0 because the former will make your base strong and so you may not have any trouble in learning the latter one.

Overall, i believe the choice is your's. If however, you need an e-book for OpenGL ES, you can ask me for it. I shall paste the link here.

# Answer
> 4 votes
OpenGL ES 2 is the best choice for Android if you are not seeking for backcompatibility.

Take a look at this tutorial https://code.google.com/p/gdc2011-android-opengl/ it's well explained.

# Answer
> 2 votes
ES 2.0 does have a steeper learning curve and you don't really need it to get started or learn alot of useful things about opengl programming. Even with ES 2.0, you'll probably build a fixed function library, similar to ES 1.x for drawing graphics primitives.

So I would say, stick with OpenGL ES 1.x for now and when you master that you can try ES 2.0 and shaders later. Most games only need a couple basic shaders unless you are doing something special. Here is a good tutorial for 2.0 shaders in android. http://blog.shayanjaved.com/2011/03/13/shaders-android/

Also, there are engines which do all the opengl work for you. If you like Java then maybe libGDX (http://libgdx.badlogicgames.com/) and if you like C++ then maybe cocos2d-x (http://www.cocos2d-x.org/projects/cocos2d-x/wiki)

# Answer
> 2 votes
OpenGL ES 2.0 is not more complex then ES 1.0 We switched to ES 2.0 and do not support ES 1.0 in real apps. ES 2.0 is supported on iPhone 3GS and newer. It is most iOS market now. On Android situation is similar but there are much more devices on market.

I recommend to learn and use ES 2.0 because you have to know ES 2.0 You should know ES 2.0 or both People how know ES 1.0 have to learn 2.0

ES 2.0 requires shader but you can add shader in 5 lines of code

If ES 1.0 code was compatible with ES 2.0 you could learn it first. But it is different. You will waste time learning ES 1.0 and switching to ES 2.0 later.

It is time for ES 2.0 especially if you learn something.

# Answer
> 1 votes
Well, If you are having only 2D contents then OpenGL ES 1 would be fine, but if you are intending to have 3D content then OpenGL ES 2 would be appropriate.

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


# Question
Title: Easy to use cross-platform 3D engines for C++ game development?
I want to try my hand at writing a 3D game. However I don't want to start at such a low level of drawing individual triangles and writing my own 3D object loader and so on. I've heard of things like Irrlicht, Crystal Space 3D, and Cafu, but I don't have any experience with any of them. I'm looking for suggestions from people who have experience with these or other engines on which ones are well written, and are easy to get started using, without having to learn a ton of 3D math theory and how GPUs work internally.

# Answer
> 51 votes
My Opinion (only for open source 3D engines):

* Irrlicht:
    + Light 3D engine
    + Clean C++ without dependencies and no STL.
    + Not very well documented but there are good tutorials.
    + Very small so you can customize it easily.
    + No OpenGL 3.X driver, Direct X 10.X or 11.X available in the official SDK.
    + Very good for mobile development;
    + Good community
    + Few extensions available
* Ogre3D:
    + Big 3D engine
    + It uses modern C++ such as STL, exceptions and RTTI
    + Good documentation (There are published books).
    + Many renderers (OpenGL, DirectX and OpenGL ES...).
    + Ogre3D have many extensions as CEGUI or Bullet integration, Tree nodes...
    + But more difficult to extend Ogre3D if you want something specifics.
    + Big community
    + Many extensions
* Crystal space: An old design and difficult to use. After few days, I stopped using this engine.
* Horde3D
    + Small engine
    + Modern design
    + Light community
    + No extensions
* Blendelf
    + Small engine with some dependencies
    + Modern design with moderns effects as DOF or HDR ...
    + OpenGL only
    + Light community
    + Bullet integration for physics
    + You use lua to pilot this engine3D

**TL;DR:**

* For a desktop game (or future commercial game): Ogre3D
* For a first game: Irrlicht
* For mobile development: irrlicht (Ogre3D is too big)
* For sexy effects: Blendelf

# Answer
> 21 votes
The obvious initial suggestion is Ogre3D.

# Answer
> 7 votes
Open Scene Graph is a pretty good, very well designed cross-platform 3D engine. Contrary to Ogre3D, for example, it does not provide "game engine" features, and concentrates on being a very nice abstraction on top of OpenGL.

* It is quite lightweight, and does not force a framework on you: you can use as little or as much of it as you want, and use it through SDL, SFML, wxWidgets, QT...
* It is a great learning experience: as you learn the library, you understand more and more about the underlying OpenGL and the way it has been designed
* Pretty much ready to use: it has loaders for mainstream 3D formats
* Shaders friendly

Have a look at the extensive list of samples.

# Answer
> 4 votes
In terms of game engines:

* Torque3D: Lots of features, but some would consider the code difficult to work with.
* C4 Engine: Inexpensive, excellent author support, but the tools could use a bit of work.
* DIY: Select a set of libraries and glue them together with your game.

Since Ogre3D was suggested, there also exists a light-weight alternative Horde3D.

Pros:

* The design is sound and will likely outperform Ogre3D for heavy rendering (if it doesn't already)
* C API, making bindings for languages like Python simple and easy to maintain (internal code is C++)

Cons:

* Requires at least OpenGL 2.0 support
* Smaller community
* Unstable code base (major architectural changes are still occurring)

# Answer
> 4 votes
Irrlicht provides a bit more than Ogre3D, and at the same time is a bit more hands-on (e.g. it doesn't feel like you're just "starting an engine" and watching it run, it feels more like you're the one running commands, as it should be in my opinion).

I think it would be great to start with!

# Answer
> 4 votes
I know you asked for C++, but Panda3D also works with C++, even if it's at first targeted to work with python. It is a game engine, but whatever...

# Answer
> 3 votes
The obvious choice, if Ogre3D is too low level for you, would be NeoAxis: http://www.neoaxisgroup.com/

It's powered by Ogre, but is a complete game development platform.

It's targeting .NET so you can use C#, managed C++, VB.

So go for that. :)

Ogre3D is able to run on a range of mobile devices, like iPhone and Android. So it's not too big.

Don't mistake size for performance.

I am not sure if IrrLicht has an official iPhone support, but Ogre3D does.

# Answer
> 2 votes
SSG: A Simple Scene Graph API for OpenGL

Open Scene Graph

OpenSG

# Answer
> 1 votes
Good answers so far, but I'll add Marmalade. It does mobile pretty well. A bunch of large studios have released console game with it, so it's got credentials. There is even a unity-like editor built on top of it, Shiva3D, which allows for cross-platform as well.

---
Tags: c++, 3d, cross-platform
---


# Question
Title: How to visually "connect" skybox edges with terrain model
I'm working on a simple airplane game where I use skybox cube rendered using disabled depth test.
Very close to the bottom side of the skybox is my terrain model.

What bothers me is that the terrain is not *connected* to the skybox bottom. This is not visible while the plane flies low, but as it gets some altitude, the terrain looks smaller because of the perspective. Since the skybox center is always same as the camera position, the skybox moves with the plane, but the terrain goes into the distance.

Ok, I think you understand the problem. My question is how to fix it.
It's an airplane game so limiting max altitude is not possible. I thought about some way to *stretch* terrain to always cover whole bottom side of the skybox cube, but that doesn't feel right and I don't even know how would I calculate new terrain dimensions every frame.

Here are some screenshot of games where you can clearly see the problem:
(oops, I cannot post images yet)

# Answer
> 3 votes
The simplest and often used solution is to use fog far away, to hide the places you don't want to be seen. It's used more often than you may think ;)

# Answer
> 2 votes
The quick fix, which works for low altitudes, is simply to extend the skybox texture further down.

Of course, you also need to make sure that your terrain actually extends all the way to where the horizon would be from the player's viewpoint. Skybox or no skybox, having the terrain just suddenly cut off isn't going to look good.

The real problem, however, is that if the player can fly, you can no longer safely treat everything in the sky as being infinitely far away. Just as an obvious example, the player should presumably be able to fly *through* a cloud; that's not going to work too well if the clouds are just textures on a skybox.

Instead, my suggestion would be to render clouds as actual objects in the game; you can use tricks like billboarding to keep them simple, at least as long as the player doesn't fly too close to them, but they should still be actual objects with a real 3D position. Your skybox should be reserved for things that can be safely treated as being infinitely far away, even from an airplane, such as astronomical objects like the sun, the moon and the stars.

As for the blue color of clear daytime sky (and the red and orange of sunrises and sunsets), that's actually somewhat tricky. In reality, it's caused by sunlight scattering off the air all around you, and its hue does depend on altitude (among other things) — the higher you go, the darker the sky looks above you. You probably want to include as part of your skybox, but generate it dynamically based on a formula that takes altitude into account. For realistic high-altitude horizons, you'll also want to apply some distance fogging to your terrain (and other objects) to simulate aerial perspective (which is also caused by atmospheric scattering).

# Answer
> 1 votes
You wouldn't stretch the ground. As you gain altitude, you can see more of the terrain as the horizon expands, but it also appears smaller. The terrain covers less of your 2D projection in the air than on the ground. The difference is where previously unseen parts of your skybox will appear, and they have to show up as skies.

If at any point the bottom face of the skybox is visible, which seems unlikely unless the box is centered above the camera or you're reaching absurd altitudes, then that side too should have a neat blue texture with clouds.

# Answer
> 1 votes
Make the terrain round. Then the last ring of polygons sepperate into a different object. The inner circle should use an opaque material, while the outer ring should use a transparent material (with same texture) but uses vert color alpha to fade away.

So, on the ring mesh, make the inner ring of vertices 100% opaque, and the outer ring 100% transparent. Extend the outer ring of vertices away for the desired amount of fading out.

Make sure the whole ground (the 2 objects) is much larger than what the player can move into so they can't reach that edge. That way, regardless of height, or distance it's always going to blend on the edges with the skybox. Just make sure your skybox bottom texture is quite close in color to your fog and all should be fine.

---
Tags: opengl-es2
---


title: Kinect Hand tracking in xna

text:
# Question
Title: Kinect Hand tracking in xna
I'm trying to create an application using the Kinect to simulate the following project:

Kinect Hand Tracking

I want my project to have similar usability with the Kinect tracking hand and finger positions for use in a menu system, or to navigate another system.

What I would like to know is; is it possible for the exact same to be accomplished in XNA using Kinect?

I know that it can be done in Winform / C#, but I know XNA / C# a lot better and would (ideally) prefer to use that.

# Answer
XNA doesn't natively support Kinect, so you've got to use the Kinect SDK and XNA in conjunction with each other.

However, you can use the two together fairly easily. There's a pretty good blog over here that will get you from installing the SDKs all the way up to Skeletal Tracking.

The blog posts are a bit old, but all the information contained in them are still relevant.

Do note, that this is only for PC development. Kinect support is not included for XNA on the Xbox 360.
> 1 votes

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


# Question
Title: How can I move a sprite in the direction it is facing?
I'm using Java/Slick 2D. I'm trying to use the mouse to rotate the sprite and the arrow keys to move the sprite. I can get the sprite to rotate no problem, but I cannot get it to move in the direction it is supposed to. When I hit "forwards", the sprite doesn't necessarily move towards the mouse. Actually, it will only move towards the left of the screen really. I'm sure there has to be some standard code for this since many games use this style of motion. Can anyone help me out with what the trig is supposed to be? Thanks

EDIT: Here is the rotation code (which does something else weird: https://stackoverflow.com/questions/12610320/why-is-my-image-rotating-off-center)

```
int mX = Mouse.getX();
        int mY = HEIGHT - Mouse.getY();
        int pX = sprite.x;
        int pY = sprite.y;
        int tempY, tempX;
        double mAng, pAng = sprite.angle;
        double angRotate=0;

        if(mX!=pX){
            mAng = Math.toDegrees(Math.atan2(mY - pY, mX - pX));
            if(mAng==0 && mX<=pX)
                mAng=180;
        }
        else{
            if(mY>pY)
                mAng=90;
            else
                mAng=270;
        }

        sprite.angle = mAng;
        sprite.image.setRotation((float) mAng);

```

And the movement code. I can only move towards the left of the screen...

```
double ang = sprite.angle;
            Input input = gc.getInput();

            if(input.isKeyDown(sprite.up)){
                sprite.x += Math.cos(ang)*sprite.moveSpeed;
                sprite.y += Math.sin(ang)*sprite.moveSpeed;
            }if (input.isKeyDown(sprite.down)){
                sprite.x += -1*Math.cos(ang*Math.PI/180)*sprite.moveSpeed;
                sprite.y += -1*Math.sin(ang*Math.PI/180)*sprite.moveSpeed;
            }if (input.isKeyDown(sprite.left)){
                sprite.x -= Math.cos(ang*Math.PI/180)*sprite.moveSpeed;
                sprite.y += Math.sin(ang*Math.PI/180)*sprite.moveSpeed;
            }if (input.isKeyDown(sprite.right)){
                sprite.x += Math.cos(ang*Math.PI/180)*sprite.moveSpeed;
                sprite.y -= Math.sin(ang*Math.PI/180)*sprite.moveSpeed;
            }

```

# Answer
You'll want to get a vector based on your current velocity and heading. Then use that vector to increment your position.

```
//first get the direction the entity is pointed
direction.x = (float) Math.cos(Math.toRadians(rotation));
direction.y = (float) Math.sin(Math.toRadians(rotation));
if (direction.length() > 0) {
    direction = direction.normalise();
}
//Then scale it by the current speed to get the velocity
velocity.x = direction.x * speed;
velocity.y = direction.y * speed;

```

So now you know your velocity based on your rotation. You can the update your position with that information.

```
//Update the position based on our current speed
//This is basic s = vt physics
position.x += velocity.x * timeElapsed;
position.y += velocity.y * timeElapsed;

```
> 16 votes

# Answer
You get the mouse position

```
mouseX = ...
mouseY = ...

```

You get the sprite position

```
spriteX = ...
spriteY = ...

```

You find the angle

```
angle = Math.atan2(mouseY - spriteY, mouseX - spriteX);

```

Your movement will be:

```
moveX = Math.cos(angle) * speed * time;
moveY = Math.sin(angle) * speed * time;

```
> 3 votes

---
Tags: java, sprites, rotation, movement, slick
---


title: Collision and Graphics integration

text:
# Question
Title: Collision and Graphics integration
I'm a little confused about the integration between collision and graphics. They both need to share the same position in the world. The most obvious choice is the center of the entity, which is good for bounding volumes and fixed sized sprites. However, for characters with variable height size sprites like this:

http://gamemedia.wcgame.ru/data/2011-07-17/game-sprite-sheet.jpg

This is no longer good. The character won't align to the ground if I'll draw it from the center. I can just make the sprites the same height, but it will be a waste of memory (the largest sprite is 4 times larger then the smallest one). Even then, this is not an option at all with skeletal sprites like this one:

http://user-generated-content.java-gaming.org/img-vault/212a171fc1ebb27ab77608fb9b2dd9bd9205361ce6300b21a7f8d06d025fbbd8.png

It seems that the graphics need to be drawn from the ground for characters, but not for other images such as scenery and obstacles. The only solution I could think of was having another position called draw-position, which is the entity center for images, and is the the bottom of the collision volume for characters. Then when I draw relative to that position, it should work properly.

I haven't found any references for something like that, so I'm kinda insecure about it. Does anyone knows of a better approach for this problem?

Thanks

# Answer
My solution to this problem may be a bit overkill, but essentially I break things up like this:

**Collision**

* Entities have a bounding box, which is essentially just a rectangle with an additional point called the "origin". The origin does not have to be the top-left corner or the rectangle. All edges of the box are calculated relative to the box's origin.
* Collisions are checked against this bounding box's edges (which are relative to the origin).

**Rendering**

* Every frame of an animation has a "source rectangle" that describes the region of the image that should be drawn.
* Each frame also has a coordinate called an "origin". This is similar to the origin of a bounding box described above.

When an entity is rendered, its animation is drawn relative to the origin of its bounding box, offset by the current animation's current frame's origin.

**Why?**

Using a method like this allows:

* each animation frame to be a different shape and size
* allows the bounding box of the character to be independent from the animation
* allows the bounding box to change in size without affecting the animation
* allows you to make the "origin" of a character at its feet or its head or its center or wherever you want it to be, and you can position an animation appropriately
> 1 votes

# Answer
Your idea for a draw-position and drawing relative to that is the correct one.

When using collision and physics, you often want a proxy shape that is much simpler than your graphics shape. For example, a box or capsule could be the collision proxy. The graphics/drawing shape is attached (drawn relative to) the collision/proxy shape.

Equally important to drawing, a simple convex proxy shape doesn't get stuck on the terrain is collisions are easy to compute.
> 0 votes

# Answer
They don't need to integrate, you can do a bounding box check and give it the position vector and the texture object as parameters, and the bounding box method can use texture2.Width/Height to determine the dimensions.

It just really depends on how you go about implementing it. When using Bounding Box, you can implement a callback on your sprite object to react to a collision, or you can simply call a method that returns a boolean type on whether the 2 objects collided.

In most physics engines you have to create objects in the graphics engines and the physics engine separately. These objects should have the same position, and dimensions.

The problem you're probably facing is the anchor point in which graphics are drawn, and the anchor point in which collisions are check are different. Perhaps you're anchoring your graphics from the top left, and the AABB(bounding box) check anchors from the center. An easy fix for this is to find the center of your texture in reference to the screen, and submit that to the AABB method rather than your x/y which is anchored at the top left.

Example:

````
bool AABB(Texture2 tex, Vector2 xy){...}
...
Texture2 image;
Vector2 pos=new Vector2(50,50);
Vector2 origin=new Vector2(image.Width/2, image.Height/2); //center of the image in reference to the image
...
bool isColliding=AABB(image, Vector2.Add(pos,origin)); //pos+origin=center of the image in reference to the screen coordinate system.

````
> 0 votes

---
Tags: collision-detection, graphics, sprites, collision-resolution
---


title: returning correct multiTouch id

text:
# Question
Title: returning correct multiTouch id
I've spent countless hours on reading tutorials and looking at every question related to multiTouch from here and Stackoverflow. But I just cannot figure out how to do this correctly. I use a loop to get my `pointerId`, I dont see alot of people doing this but its the only way I've managed to get it somewhat working.

I have two joysticks on my screen, one for moving and one for controlling my sprites rotation and the angle he shoots, like in Monster Shooter. Both these work fine.

My problem is that when I Move my sprite at the same time as Im shooting, my `touchingPoint` for my movement is set to the `touchingPoint` of my shooting, since the `x` and `y` is higher on the `touchingPoint` of my shooting (`moving-stick` on left side of screen, `shooting-stick` on right side), my sprite speeds up, this creates an unwanted change in speed for my sprite.

this is how I solved it with your help! this is for anyone that might run into a similar problem:

```
    public void update(MotionEvent event) {
    if (event == null && lastEvent == null) {
        return;
    } else if (event == null && lastEvent != null) {
        event = lastEvent;
    } else {
        lastEvent = event;
    }

        int action = event.getAction();
        int actionCode = action & MotionEvent.ACTION_MASK;
        int pid = action >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
        int x = (int) event.getX(pid);
        int y = (int) event.getY(pid);
        int index = event.getActionIndex();
        int id = event.getPointerId(index);
        String actionString = null;

        switch (actionCode)
        {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_DOWN:

                actionString = "DOWN";
                try{
                    if(x > 0 && x < steeringxMesh + (joystick.get_joystickBg().getWidth() * 2)
                            && y > yMesh - (joystick.get_joystickBg().getHeight()) && y < panel.getHeight()){
                            movingPoint.x = x;
                            movingPoint.y = y;
                            dragging = true;
                            draggingId = id;

                        }
                    else if(x > shootingxMesh - (joystick.get_joystickBg().getWidth()) && x < panel.getWidth()
                            && y > yMesh - (joystick.get_joystickBg().getHeight()) && y < panel.getHeight()){
                            shootingPoint.x = x;
                            shootingPoint.y = y;
                            shooting=true;
                            shootingId=id;
                        }
                    }catch(Exception e){

                    }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_OUTSIDE:
                if(id == draggingId)
                    dragging = false;
                if(id ==  shootingId)
                    shooting = false;
                actionString = "UP";
                break;
            case MotionEvent.ACTION_MOVE:
                for(index=0; index<event.getPointerCount(); index++) {
                    id=event.getPointerId(index);
                    int xx = (int) event.getX(index); //pro naming of variable
                    int yy = (int) event.getY(index);
                    if(dragging && id == draggingId) {
                        if(xx > 0 && xx < (steeringxMesh + joystick.get_joystickBg().getWidth() * 2)
                            && yy > yMesh - (joystick.get_joystickBg().getHeight()) && yy < panel.getHeight()) {
                            movingPoint.x = xx;
                            movingPoint.y = yy;
                        }
                        else
                            dragging = false;
                        }
                    if(shooting && id == shootingId){
                        if(xx > shootingxMesh - (joystick.get_joystickBg().getWidth()) && xx < panel.getWidth()
                            && yy > yMesh - (joystick.get_joystickBg().getHeight()) && yy < panel.getHeight()) {
                            shootingPoint.x = xx;
                            shootingPoint.y = yy;
                        }
                        else
                            shooting = false;
                        }
                    }

                    actionString = "MOVE";
                    break;

        }
    Log.d(TAG, "actionsString: " + actionString + ", pid: " + pid + ", x: " + x + ", y: " + y);

```

Wouldnt post this much code if I wasnt at an absolute loss of what I'm doing wrong. I simply can not get a good understanding of how multiTouching works.

basicly `movingPoint` changes for both my first and second finger. I bind it to a box, but aslong as I hold one finger within this box, it changes its value based on where my second finger touches. It moves in the right direction and nothing gives an error, the problem is the speed-change, its almost like it adds up the two touchingPoints.

# Answer
> 4 votes
I think this will work for you.

One mistake you made was iterating over all pointers for every event. It's only necessary for move events.

Secondly, you actually do need to put the index value into the getX and getY functions, but you get the id associated with that index to use as a reference to your game objects. You assign an id to your joystick during the Down Event and then when iterating through your pointer indices, check if the index is associated with the pointer id that you assigned to the joystick during the Down event. If it is, check if it is still in bounds and either update it or disable it.

I am not testing this code, but I know it works in concept because I use the method in my own code. Let me know if there are any problems with it that you can't figure out.

First, you will have to add the following to your joystick class.

```
boolean dragging=false;
int draggingId;
boolean shooting=false;
int shootingId;

```

Change your onTouchEvent to this.

```
public boolean onTouchEvent(MotionEvent event) {

    int index = event.getActionIndex();
    int id = event.getPointerId(index);
    String actionString;

    switch (event.getActionMasked()) {
        case MotionEvent.ACTION_DOWN:
            try{
                    if(x > 0 && x < steeringxMesh + joystick.get_joystickBg().getWidth() * 2)
                        && y > yMesh - (joystick.get_joystickBg().getHeight()) && y < panel.getHeight()
                        && !joystick.dragging) {
                            movingPoint.x = x;
                            movingPoint.y = y;
                            joystick.dragging = true;
                            joystick.draggingId = id;
                    }
                    else if(x > shootingxMesh - (joystick.get_joystickBg().getWidth()) && x < panel.getWidth()
                        && y > yMesh - (joystick.get_joystickBg().getHeight()) && y < panel.getHeight()
                        && !joystick.shooting) {
                            shootingPoint.x = x;
                            shootingPoint.y = y;
                            joystick.shooting=true;
                            joystick.shootingId=id;
                    }
              }
              catch(Exception e){

              }

            actionString = "DOWN";
            break;
        case MotionEvent.ACTION_UP:
            if(id == draggingID)
                joystick.dragging = false;
            if(id ==  shootingID)
                joystick.shooting = false;
            actionString = "UP";
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            try{
                    if(x > 0 && x < steeringxMesh + joystick.get_joystickBg().getWidth() * 2)
                        && y > yMesh - (joystick.get_joystickBg().getHeight()) && y < panel.getHeight()
                        && !joystick.dragging) {
                            movingPoint.x = x;
                            movingPoint.y = y;
                            joystick.dragging = true;
                            joystick.draggingId = id;
                    }
                    else if(x > shootingxMesh - (joystick.get_joystickBg().getWidth()) && x < panel.getWidth()
                        && y > yMesh - (joystick.get_joystickBg().getHeight()) && y < panel.getHeight()
                        && !joystick.shooting) {
                            shootingPoint.x = x;
                            shootingPoint.y = y;
                            joystick.shooting=true;
                            joystick.shootingId=id;
                    }
              }
              catch(Exception e){

              }

            actionString = "PNTR DOWN";
            break;
        case MotionEvent.ACTION_POINTER_UP:
            if(id == joystick.draggingID)
                joystick.dragging = false;
            if(id ==  joystick.shootingID)
                joystick.shooting = false;
            actionString = "PNTR UP";
            break;
        case MotionEvent.ACTION_CANCEL:
            if(id == joystick.draggingID)
                joystick.dragging = false;
            if(id ==  joystick.shootingID)
                joystick.shooting = false;
            actionString = "CANCEL";
            break;
        case MotionEvent.ACTION_MOVE:
            for(index=0; index<e.getPointerCount(); index++) {
                id=e.getPointerId(index);
                int x = (int) event.getX(index);
                int y = (int) event.getY(index);
                if(joystick.dragging && id == joystick.draggingId) {
                    if(x > 0 && x < steeringxMesh + joystick.get_joystickBg().getWidth() * 2)
                        && y > yMesh - (joystick.get_joystickBg().getHeight()) && y < panel.getHeight()) {
                        movingPoint.x = x;
                        movingPoint.y = y;
                    }
                    else
                        dragging = false;
                    }
                }
                else if(joystick.shooting && id == joystick.shootingId){
                    if(x > shootingxMesh - (joystick.get_joystickBg().getWidth()) && x < panel.getWidth()
                        && y > yMesh - (joystick.get_joystickBg().getHeight()) && y < panel.getHeight()) {
                        shootingPoint.x = x;
                        shootingPoint.y = y;
                    }
                    else
                        shooting = false;
                    }
                }
            }
            actionString = "MOVE";
            break;
        }
    }

```

# Answer
> 7 votes
You are almost getting it right, but you should use your pointer id to request the X/Y instead of `i`

```
    int id = event.getPointerId(i);
    int x = (int) event.getX(id);
    int y = (int) event.getY(id);

```

From the MotionEvent documentation:

> The order in which individual pointers appear within a motion event is undefined. Thus the pointer index of a pointer can change from one event to the next but the pointer id of a pointer is guaranteed to remain constant as long as the pointer remains active. Use the getPointerId(int) method to obtain the pointer id of a pointer to track it across all subsequent motion events in a gesture. Then for successive motion events, use the findPointerIndex(int) method to obtain the pointer index for a given pointer id in that motion event.

`event.getX/Y` require a pointer id, not `i`, because there's no garantee they'll be in the same order.

In addition, there is another subtle but important problem. Notice how the getAction() family of function do not take a parameter. That's kind of weird, right? Getting X/Y requires the pointer id, but not the action performed? That is hinting at a couple of important things:

* you get a call to you touch handler for each action of each pointer and not a single call per frame for all pointers
* getX/Y looks at the trace of the pointer so far and returns the latest value, while getAction inquires about the current event only

So that means you get ***one*** call to your touch handler ***per pointer action*** (down/move/up). So two fingers moving = 2 calls. A nasty side effect of your code is that it applies the action of one event to all the pointers...

So, instead of looping over the traces, simply get the pid/x/y/action for the current event only (for simultaneous movement, you will get another call to your handler a tiny bit later, like I said)

Here is my code to handle events:

```
 public static boolean sendTouchToGameEngine (MotionEvent event)
 {
  int action = event.getAction();
  int actionCode = action & MotionEvent.ACTION_MASK;
  int pid = action >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;

  [...]
  sendTouchToGameEngine(pid, actionCode, (int)event.getX(pid), (int)event.getY(pid));
  [...]

  return true;

```

}

To go back to your code, you should be able to simplify it in the following way. The loop is gone, otherwise, if you have other contraints that you didn't mention, you can always add it back. It works by tracking which pointer id is used for which control (move/shoot) when DOWN is triggered and reseting them on UP. Since you don't use gestures, you can restrict your switch() to DOWN, UP, MOVE and OUTSIDE.

```
int movePointerId = -1;
int shootingPointerId = -1;

void TouchEventHandler(MotionEvent event) {
    // grab the pointer id
    int pid = action >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
    int x = (int) event.getX(pid);
    int y = (int) event.getY(pid);
    int action = event.getAction();
    int actionCode = action & MotionEvent.ACTION_MASK;
    int actionIndex = event.getActionIndex();
    String actionString;

    switch (actionCode)
    {
        case MotionEvent.ACTION_DOWN:
        // on DOWN, figure out whether the player used the moving or shooting control, if any.
        // if so, kept track of which pointer was used, because all following call about that
        // finger touches will use the same pointer id. Also record the current point coordinates.
            actionString = "DOWN";
            try{
                if(x > 0 && x < steeringxMesh + (joystick.get_joystickBg().getWidth() * 2)
                        && y > yMesh - (joystick.get_joystickBg().getHeight()) && y < panel.getHeight()){
                        movingPoint.x = x;
                        movingPoint.y = y;
                        movePointerId = pid;
                    }
                else if(x > shootingxMesh - (joystick.get_joystickBg().getWidth()) && x < panel.getWidth()
                        && y > yMesh - (joystick.get_joystickBg().getHeight()) && y < panel.getHeight()){
                        shootingPoint.x = x;
                        shootingPoint.y = y;
                        shootingPointerId = pid;
                    }
                }catch(Exception e){

                }
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_OUTSIDE:
        // whether the player lift the finger or moves it out of bounds
        // figure out which pointer that was and reset it. You can add additional
        // processing here as required
           if( pid == movePointerId )
              movePointerId = -1;
           else if( pid == shootingPointerId )
              shootingPointerId = -1;
            actionString = "UP";
            break;
        case MotionEvent.ACTION_MOVE:
        // when the player move their finger, it is simply a matter of comparing the pid
        // to know which one it is
          if( pid == movePointerId ) {
                        movingPoint.x = x;
                        movingPoint.y = y;
          } else if( pid == shootingPointerId ) {
                        shootingPoint.x = x;
                        shootingPoint.y = y;
          }
                actionString = "MOVE";

    }
}

```

# Answer
> 0 votes
There's a little weirdness going on with this code. I don't use Android, so maybe I'm thinking this is something it's not. However I did notice that you're getting the position twice, in two different ways:

First you get it like this at the start of your `pointerCount` loop:

```
(int) event.getX(i)

```

Then, inside your switch statement you get it like so:

```
(int) event.getX(id)

```

Notice that you switch from using `i` to using `id`.

I'm assuming it's supposed to be the former method. I recommend replacing all of the instances of `(int) event.getX(id)` and use the value `x` you set at the beginning. Likewise swapping `(int) event.getY(id)` to `y`.

Try swapping out these parts:

```
int pointerCount = event.getPointerCount();
for (int i = 0; i < pointerCount; i++)
{
    int x = (int) event.getX(i);
    int y = (int) event.getY(i);

```

Then inside your switch use this:

```
    try{
        if(x > 0 && x < touchingBox &&
              y > touchingBox && y < view.getHeight()){
            movingPoint.x = x;
            movingPoint.y = y;
            dragging = true;
        }
        else if(x > touchingBox && x < view.getWidth() &&
                   y > touchingBox && y < view.getHeight()){
            shootingPoint.x = x;
            shootingPoint.y = y;
            shooting=true;
        }else{
            shooting=false;
            dragging=false;
        }

```

# Answer
> 0 votes
I had a similar problem once on a Huawei U8150. The two finger multitouch on that device was really bad, using a multitouch test app (maybe it was "Phone Tester" but I'm not sure) I was able to see that touching with the second finger moved the 1st touch spot of many pixels. If that's your problem than it's hardware related and I don't think you can do much for it :(

Sorry for my bad english

# Answer
> 0 votes
I believe your problem is that you are assuming that, between updates, the order in which the pointers are arranged stays the same. That's most likely not going to be the case.

Imagine a situation where you touch with finger A. There will be a pointerCount() of 1, and A will be the only element you can ask about. If you add a second finger, the pointerCount() will be 2, A will be at index 0, B will be at index 1. If you raise finger A, pointerCount() will be 1 again, and **B will be at index 0**. If you then touch with finger A again, **A will be at index 1 and B will be at index 0**.

This is why the pointer ID is provided, so that you can track individual touches between updates. So if the first touch of finger B is assigned the ID 12, it will always have that ID, even when finger A is removed and re-added.

So if your code identifies a touch near your shooting joystick, it must check to see if there is already a 'shooting' touch in progress. If not, then the ID of the shooting touch should be remembered in some member variable that persists to the next update. In subsequent updates, if you have a 'shooting' touch in progress, iterate through the pointers and look for the pointer with the right ID, and it's that pointer you need to use to track updates for, and all others can be ignored. Same for the movement touch. When the touch is released, you clear the ID associated with that joystick so that a new touch can take control of it.

Even if a touch that starts near one joystick strays far away from the original touch position, by its ID you can still correctly identify what joystick it is controlling. And as a nice side effect, a second stray finger near a particular joystick won't have any effect, because the joystick will be bound to the first finger that triggered it until it is release.

---
Tags: android, movement, multitouch
---


title: Ideas for 2d fire simulation

text:
# Question
Title: Ideas for 2d fire simulation
I want to simulate a fire in a flat and non flat\* surface (fire spread modelling).

I've seen that cellular automata is one of the algorithms that can be used. Are there other algorithms that would be interesting to test?

\*adding some barriers like walls

# Answer
> 2 votes
Easy. Particle system. Flammable objects have a constant boolean for flammability set to True, then another boolean which dictates if the object is on fire. If true spawn a particle system on them to give it an effect which makes it look like its on fire. If a flaming object collides with another, then set that object on fire. You may want to spread the flame only after the objects have made contact for a certain duration, or all connected flammable objects would light instantly.

I've done something similar with the Love2D Engine

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


# Question
Title: Checking for alternate keys with XNA IsKeyDown
I'm working on picking up XNA and this was a confusing point for me.

```
KeyboardState keyState = Keyboard.GetState();
if (keyState.IsKeyDown(Keys.Left) || keyState.IsKeyDown(Keys.A))
{
    //Do stuff...
}

```

The book I'm using (Learning XNA 4.0, O'Rielly) says that this method accepts a bitwise OR series of keys, which I think should look like this...

```
KeyboardState keyState = Keyboard.GetState();
if (keyState.IsKeyDown(Keys.Left | Keys.A))
{
    //Do stuff...
}

```

But I can't get it work. I also tried using `!IsKeyUp(... | ...)` as it said that all keys had to be down for it to be true, but had no luck with that either. Ideas? Thanks.

# Answer
> 10 votes
The XNA Keys struct is not marked with the Flags Attribute which means that it's *not* legal to | a load of keys together like that.

```
Keys keyCombo = Keys.Left | Keys.A;
Console.WriteLine(keyCombo);

```

Will print **NumPad5**, which is clearly not what you want here! You've never been able to do this in any version of XNA, I think the book is just wrong here :O

Copying from one of my own games, this is how I solved it:

```
#if WINDOWS
public static bool Any(this KeyboardState state, params Keys[] keys)
{
    return keys.Any(state.IsKeyDown);
}
#endif

```

And then you can just do:

```
KeyboardState k = Keyboard.GetState();

if (k.Any(Keys.Left, Keys.A))
    DoStuff();

```

However, as someone in the comments pointed out **this method is bad practice on the xbox** due to it allocating (params array allocation, and LINQ allocating an Enumerator). An alternative system for xbox is this:

```
Keys[] doStuffKeys; //Allocate an array of keys for this particular action

Initialize()
{
    doStuffKeyBinding = new[] { Keys.Left, Keys.A };
}

Update()
{
    KeyboardState k = Keyboard.GetState();

    if (k.Any(doStuffKeys)) //No allocations here!
        DoStuff();
}

```

The Any method needs modifying too:

```
#if XBOX
public static bool Any(this KeyboardState state, Keys[] keys)
{
    for (int i = 0; i < keys.Length; i++)
        if (state.IsKeyDown(keys[i]))
            return true;
    return false;
}
#endif

```

It's a while since I've done any work for the xbox, but this now shouldn't allocate.

# Answer
> 4 votes
`IsKeyDown` takes an enum `Key` for its type. I don't see from the documentation that it can take multiple emums ORed together. Perhaps your book is wrong?

You could create your own method if you wanted the shortcut:

```
boolean anyOfTheseDown(KeyboardState keyState, params Keys[] keys) {
   boolean result = false;
   for (int i = 0; i < keys.Length; i++)
   {
       result |= keyState.IsKeyDown(keys[i]);
   }
   return result;
}

```

Then use it like:

```
KeyboardState keyState = Keyboard.GetState();
if (anyOfTheseDown(keyState, Keys.Left, Keys.A))
{
    //Do stuff...
}

```

Code is untested.

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


# Question
Title: When tracing how do I tell if I hit a wall or floor?
I perform a trace and when it hits the world I get a location and the surface normal. Does anyone have a good way to find out if I hit a wall or a floor?

# Answer
What Thomas said in his comment: the surface normals on the floor are pointed up, while the walls are pointed sideways.

(I'm leaving my response about the dot product because that will work too and helps explain how to work with 3D vectors, but phillips comment points out a simpler approach I didn't think of)

Just check the normal's Z component. So, if you wanted "floors" to be surfaces with normals \< 45°, you could check if the Z value is \> 0.707 (because sin(45°)=0.707). In fact, this is how Unreal checks if the Pawn is on a "floor" -- it compares the floor's normal Z value to WalkableFloorZ, which is 0.7 by default.

---

What you should probably do is get the dot product of the surface normal and a vector pointed straight up: if the trace crossed the floor then the dot product will be near 1, while if it was a wall then the dot product will be near 0, and if it was the ceiling then it'll be near -1

The threshold of how near is a value you can tune to see what works for your level:

```
var threshold = .1;
if (abs(1 - dotProduct) < threshold) {then...

```
> 2 votes

# Answer
Without knowing more about your implementation, a simple way to determine if you're hitting a wall or a floor is by taking the direction your body is moving into consideration.

* If you're moving *left or right*, and a collision occurs, then you've hit a **wall**.
* If you're moving or *falling down*, and a collision occurs, then you've hit a **floor**.

So you can use the velocity of your entity to determine the nature of the collision.
> 0 votes

# Answer
As "Zack The Human" said, you should consider which way your character is moving. Another idea is to check which side of your player/object collided. If the bottom of your character collide you either hit the floor or an object you can stand on. Another method is to provide a pointer/reference to the object you collided with and conclude from that what you collided with.

Each of them has there perks in different situations, and they can all be implemented together. For example if I'm making a platformer I check the direction my player is moving and where the object I collided with is located. This way I can conclude if my player was moving down and collided with an object under it, that is hit the floor or a platform. Same goes for walls, if my player is moving left and hits an object to the left of it, stop moving left.

You should really learn 2D before 3D. Its easier to learn the concepts.
> 0 votes

---
Tags: raycasting, udk
---