title: A* pathfinding for an isometric map

text:
# Question
Title: A* pathfinding for an isometric map
I am making an isometric tower defense game in XNA and trying to implement the A\* pathfinding algorithms for my enemy AI. I am quite new to programming, especially AI and pathfinding, so please excuse my lack of knowledge.

I am using an a\* tutorial from an XNA game programming book but it is made for standard square tile maps. I am trying to adapt this into my isometric tile engine and running into a few problems. Firstly, here are the major differences between the two maps:

Book:

* Tiles are 32x32.
* directions are up, down, left, right.
* obstacles are wall tiles

My Map:

* tiles are 64 x 64
* 4 directions: NE, NW, SE, SW
* impassable tiles

From these differences, I can figure out that I have to make changes to the grid setup, cost calculation and tile types.

I have made adjustments for the latter two, but I am having problems setting up the grid/gridnodes which is the most important part. Or perhaps, I simply don't understand the code well enough.

Here is the code for the Pathnode:

```
class PathNode
{

    public PathNode ParentNode;
    public PathNode EndNode;
    private Vector2 gridLocation;
    public float TotalCost;
    public float DirectCost;
    public Vector2 GridLocation
    {
        get { return gridLocation; }
        set
        {
            gridLocation = new Vector2(
               (float)MathHelper.Clamp(value.X, 0f, (float)50),
               (float)MathHelper.Clamp(value.Y, 0f, (float)50));
        }
    }

    public int GridX
    {
        get { return (int)gridLocation.X; }
    }

    public int GridY
    {
        get { return (int)gridLocation.Y; }
    }

    public PathNode(
        PathNode parentNode,
        PathNode endNode,
        Vector2 gridLocation,
        float cost)
    {
        ParentNode = parentNode;
        GridLocation = gridLocation;
        EndNode = endNode;
        DirectCost = cost;
        if (!(endNode == null))
        {
            TotalCost = DirectCost + LinearCost();
        }
    }

    public float LinearCost()
    {
        return (
            Vector2.Distance(
            EndNode.GridLocation,
            this.GridLocation));
    }

    public bool IsEqualToNode(PathNode node)
    {
        return (GridLocation == node.GridLocation);
    }

}

```

What should I change in this class to adapt this `pathnode.cs` to an isometric map? It is probably the gridLocation property but I am stumped as to what should be in there.

Any other tips on isometric pathfinding would be greatly appreciated!

# Answer
Can't give you code, but I'll try to help you with this problem by explaining it in a different way so that you can apply what you know to solve it.

1) Grid size shouldn't matter. The data structure in which you store objects should be agnostic about such things. Take the chess board example above. I could double or halve the size of the board, but as long as I know the coordinates, it doesn't matter for any internal mechanics, only for rendering.

2) Isometric verus normal grid also doesn't matter. Either way you have the same exact grid, it is only roated. As you can see, I took the same board and converted it to an isometric view. My pieces would still be in the same exact spot and could still use the same exact logic.

3) Impassible tiles are actually easier than walls between grids. Your program knows how to move and it already knows positions of objects in terms of grid cells. You just need to mark the object in that grid on if you can move through it or not.

I usually do this by creating data structures, one for static objects and one for objects that change. The static objects are filled with objects that tell the game how to render the map. It also says if you can move through that tile or not. Thus to see if you can move there, you get all of the objects in that grid space and check them all for the flag. If all allow you to pass, then you can move through it.
> 3 votes

---
Tags: xna, path-finding, isometric, tilemap
---


title: Managing the base HP of a game

text:
# Question
Title: Managing the base HP of a game
I'm creating a simple turn-based 2D Tile RPG in JavaScript/jQuery (using HTML5 Canvas) and the hardest part is the formulas. I got the EXP per level down. I have a base level. I'm trying to see what a reasonable way to come up with HP formula using said base level.

Any help?

# Answer
It's not a simple matter, I think you'd better follow the whole Game balance concepts course.

Either way, that one or an alternative, since if you just improvise it, almost certainly you will get a bad result *at best*.
> 5 votes

# Answer
So there is not a true answer to this question because HP is only a single factor of combat. I'm assuming that this is a turned based game. First thing to do is step back and abstract things out. I usually find one of the most important questions to be, how long do you expect combat to last, because you have a number of factors to balance.

**Dodge**: When a character attacks, do they always hit? If not, you have boosted the defender's HP (the effective HP). Say that you miss 50% of the time, you have effectively doubled the defenders HP as it will take twice as many hits to kill them.

**Resistance**: Same goes here. Does armor resist damage? Is it by a static number or a percentage? The same equation can be used to determine the effective HP. If you have 50% dodge and 50% resistance, you have quadrupled the effective HP now.

**Healing**: Can the player or the enemy heal themselves? How often and for how much?

If you want examples of how things are done, I honestly suggest finding a few tabletop RPGs and looking at the rules. They are usually simple rules because they are meant to be played with only pend and paper and the rules are fully open to you.

After that, play test it. Sit down and manually go through one of the battles. See if you like the feel of how it works. You can always also write a program to have characters battle each other multiple times with different variables. This can help you balance things as you can find that one of the variables (or weights) is set to high or low.
> 4 votes

---
Tags: game-design, balance
---


# Question
Title: OpenGL : Suggestion on handling collision detection and vertex data?
I was thinking how to do collision detection in my OpenGL application and came to conclusion that I should keep two copies of my geometry data.

1)**First copy** : Only for OpenGL rendering purposes.This can be saved as VBO,Vertex Indices.(saved in GPU?)

2)**Second copy** :I save in client side(in a class ,say 3DEntity) which I perform all tests including bounding-box collision test,ray casting,

So, after I load a mesh data (say from an OBJ file), first I prepare the "first copy" and then using "vertex indices" I prepare the "second copy". (For example: If my mesh is a simple cube ,my "first copy" will have 8 vertices,and use Vertex Indices to render it properly.But my "second copy" will have total 36 vertices.Because I have to do ray-casting on triangles)

I keep a transformation matrix inside the "3DEntity" to keep states like Position,Rotation..etc of my "3d Entity". So in psuedo code;

```
class 3DEntity {
 Vertex[] verticesForPhysics;
 Matrix tranformationMatrix;
}

```

I keep the "verticesForPhysics" values fixed.(Means, its always in model coordinate system).So When I want to move,rotate my entity I simply change "transformationMatrix".

When doing tests like collision detection , I make a temporary copy of vertices again,by multiplying "verticesForPhysics" by "transformationMatrix" giving the vertices in World coordinates.

```
Vertex[] verticesForPhysicsInWorld=transformationMatrix * verticesForPhysics;

```

Now I do my tests using these "verticesForPhysicsInWorld".

Is this the correct way of handling this ? How do other OpenGL game engines handle this ? I am worried about data redundancy by keeping two copies and making another temporary copy for collision detection tests

# Answer
> 2 votes
I think of a game as some kind of simulation that needs a real time input from a number of interactors and returns a real time output. The main objective of this simulation is that the input\<\>output interaction is fun.

There is no collisions in openGL; only drawing, which is part of the output of the "simulation". (I'm saying this because of the title).

I'm not sure you have to worry on which parts of the hardware the data is being held on a first approach. I'm not even sure you need to save the matrix transformation; you can just save the position, velocity, rotation etc of the entity. Because that is what is part of the "simulation" (in case you use more complex itens than this must be re-thought).

The collision algorithm should never be used on all the vertices you've designed for your model. That is a kind of simulation that will not run on realtime. Try to search the concept of collision box. Basically is a cube, or other simpler form, which can be used to simulate collisions without calculating with all the vertices of your model.

About the copy, I think that what you really must focus is on how the code must be designed in order to be able to let the simulation and input/output be two distinct things. For instance, given a struct/class in c/c++, there should be a function like "draw" for every entity that you want to draw onscreen (which call openGL functions). And thats it. Let openGL handle the rest.

---
Tags: opengl, 3d, collision-detection, graphics, rendering
---


title: Earth's rotation along it's axis

text:
# Question
Title: Earth's rotation along it's axis
I've modeled an earth using an sphere. I can rotate it using `glRotatef` function around z axix by incrementing the angle. How do I simulate earth's movement which looks like 23.5Degree around Z axis? (see this image)

I guess I need to calculate the x,y,z verctors. Any Idea? I'm a complete newbie in computer graphics programming.

# Answer
After applying the `glRotatef` to get the z axis rotation for time-of-day, call `glRotatef` again to get the tilt on the y (or is it x?)
> 1 votes

---
Tags: opengl, rotation
---


# Question
Title: Random generation of realistic human faces
What would be a practicable way of generating huge numbers of realistically looking human faces? Randomizing 3D-models and rendering them would require a lot of computing power, especially as I'm needing them on an ad-hoc basis. Layering individual 2D-drawn parts requires some artistic talent, which I'm definitely lacking. Also, I'd like to parameterize as many aspects of the generational process as possible. Do you have any suggestions how to go about this?

# Answer
> 4 votes
This can certainly be done - Skyrim is a good example of a game that uses procedurally generated 3D faces. Basically they take a set of standard face models and describe different geometry morphs / colour changes that can be applied in different quantities to make all kinds of different combinations.

If you are just after simple 2D faces though, I think the layering approach would work best - hire an artist to draw lots of different face features, then combine them in different combinations to create lots of different random faces. Small random offsets to each of the components will also help create some extra variety.

Links that might also be fun:

# Answer
> 1 votes
Steven's answer is a good one. Human brains are very well-versed in making fine judgements of faces, their construction as well as their facial gestures.

However, I want to pose a corollary question towards your idea. What is the state of facial recognition software? Can it reliably tell a human face from a CG one?

I'm curious as to the usefulness of hooking the output from a facial generator with a facial recognizer, with the goal of grading the humanness of the faces. Once you have a system that can produce faces and recognize the good, the bad and the ugly, is it not conceivable that the generated faces could improve over time?

I expect the implementation of this all would be challenging and complex. But I would love to see the results.

# Answer
> 1 votes
**Mix existing photos of human faces into new ones.**

There are millions of existing photos of faces available to you online. The approach I would take is to use well known feature-detection algorithms and blend together the features from different faces algorithmically.

This would give you the randomness *and* the realism.

In more details, I would create a processing pipeline for human faces, which would:

1. Detect different features (eyes, mouth, ears, forehead, chin, jaw, cheekbone, etc...)
2. Using the detected feature's locations, split the images into components.
3. Randomise the parameters of a positional and size template.
4. Place randomly selected components onto the generated template.
5. Blend the features into one another. (edge smoothing, tone, color, etc...)

Some quickly found resources:

You'll also need to get a database of faces, which might come with some licensing issues, or gather them yourself from the web, which will be time consuming.

Be warned that this kind of problem is effectively active research. I don't even want to know how long it took the Skyrim folks to get their face generation system working. (And they had decades of experience since the days on Morrowind...)

---
Tags: graphics, procedural-generation
---


title: Transform Matrix multiplication order

text:
# Question
Title: Transform Matrix multiplication order
I am experiencing difficulties trying to figure out the correct multiplication order for a final transform matrix. I always get either strange movement or distorted geometry. My current model is explained below:

For a single node my multiplication order is:

> L = S * R * T

where

> L = local transformation matrix
>
> S = local scale matrix
>
> R = local rotation matrix
>
> T = local translate matrix

For a node's world transformation:

> W = P.W * L

where

> W = world transformation matrix
>
> P.W = parent world transformation matrix
>
> L = the local transformation matrix calculated above

When rendering, for each node I calculate the matrix :

> MV = Inv(C) * N.W

where

> MV = the model view transformation matrix for a particular node
>
> Inv(C) = the inverse camera transformation matrix
>
> N.W = the node's world transformation matrix calculated above.

Finally, in the shader I have the fallowing transformation:

> TVP = PRP * MV * VP

where

> TVP = final transformed vertex position
>
> PRP = perspective matrix
>
> MV = the node's world transformation matrix calculated above
>
> VP = untransformed vertex position.

With the current model, child nodes which have local rotation, rotate strangely when transforming the camera. Where did I go wrong with the multiplication order?

# Answer
Any combination of the order `S*R*T` gives a valid transformation matrix. However, it is pretty common to first scale the object, then rotate it, then translate it:

```
L = T * R * S

```

If you do not do it in that order, then a non-uniform scaling will be affected by the previous rotation, making your object look skewed. And the rotation will be affected by the translation, making the final position of your object very different from what the value of the translation would make you expect.
> 48 votes

---
Tags: matrix
---


# Question
Title: isometric tile - How would I apply effect on only specific part of a sprite?
How would I apply a mask for pixel shading effect to restrict it only to some part of image? For example I have a height tile:

Now I want to apply the effect only on the tile-shape of this height-tile with some sort of masking:

Therefore, how would I restrict the pixel shading function boundary using masking?

# Answer
You could achieve this through (at least) two different methods. One is to use the stencil buffer, this way you could draw arbitrary shapes in pictures and use those as masks. The other option is to make the mask in a vertex buffer and thus draw only the wanted part directly in the first call.

Both would work fine, in this case the second type would probably be simplest and quickest to setup, but the first one allows a bit more artistic freedom at the cost of some complexity. Here is a pretty good example for stencil buffering and what it can do.
> 2 votes

---
Tags: xna, isometric, fragment-shader
---


title: How to implement HUD

text:
# Question
Title: How to implement HUD
I'm wondering how one could implement an HUD in LWJGL. I've seen tutorials on this, but they don't seem to work. I know the basic structure goes like this:

```
init3d();
// 3d code
init2d();
// HUD

```

To which, of course, init3d and init2d are the GL Initialization codes. And also, how would you draw the images for the HUD (or should I ask that in a separate question)?

If this is too vague, let me know and I'll update the question.

# Answer
The easiest way to handle this is to use a library that's specifically designed for GUIs. Check out Nifty GUI. It works with OpenGL + LWJGL + Slick. Follow the getting started guide and read the tutorials. Finally, check out the source code for the examples. This will get you on your way the quickest, without needing to worry so much about the lower level graphics involved.
> 3 votes

---
Tags: opengl, 2d, lwjgl, slick
---


title: Opengl tutorials

text:
# Question
Title: Opengl tutorials
> **Possible Duplicate:**
> What are some good learning resources for OpenGL?
> Starting out with OpenGL when most tutorials are out of date

I know that there are many questions like this, but i want the best answer how to learn modern opengl from basics. Also i want to avoid toolkits like glut or similar. Any books or something? Using Windows

# Answer
I think the free online book **Learning Modern 3D Graphics Programming** by Jason L. McKesson, username Nicol Bolas on GDSE, is a great place to start.

It does use FreeGLUT to create the window, but I don't really see that as a disadvantage, since it allows most of the Win32 boilerplate code to be skipped, so that the book can actually focus on modern OpenGL programming. You can easily find Win32 programming resources elsewhere, or just use GLFW or SDL.

Link - http://www.arcsynthesis.org/gltut/
> 1 votes

---
Tags: opengl, windows
---


title: Find a Rectangle by coordinates - XNA

text:
# Question
Title: Find a Rectangle by coordinates - XNA
I have 2 coordinates (X,Y). I have also a 10x10 array. By these coordinates I have to find the rectangle in which is my pointer at the moment. How could I handle it?

# Answer
If your grid array is displayed as a Rectangle(ox,oy, 10\*CELL\_SIZE, 10\*CELL\_SIZE), where (ox,oy) is an offset...

then the cell coords are

```
  xCell = (x-ox)/CELL_SIZE;
  yCell = (y-oy)/CELL_SIZE;

```

of course you should check the coords are in right range (0..9,0..9)
> 1 votes

---
Tags: xna, vector, coordinates
---


title: Time reverse mechanism in games

text:
# Question
Title: Time reverse mechanism in games
I am wondering about how time manipulation mechanisms in games are typically designed. I am particularly interested in time reversing (sort of like in the latest SSX or Prince of Persia).

The game is a 2D top down shooter.

The mechanism I am trying to design/implement has the following requirements:

1) Actions of entities apart from the player character are completely deterministic.

* The action an entity takes is based on the frames progressed since level start and/or the position of the player on the screen
* Entities are spawned at set time during the level.

2) Time reverse works by reversing back in realtime.

* Player actions are also reversed, it replays in reverse what the player performed. Player has no control during reverse time.
* There is no limit on the time spent reversing, we can reverse all the way to the beginning of the level if wanted.

As an example:

Frames 0-50: Player moves foward 20 units over this time Enemy 1 spawns at frame 20 Enemy 1 moves left 10 units during frame 30-40 Player shoots bullet at frame 45 Bullet travels 5 foward (45-50) and kills Enemy 1 at frame 50

Reversing this would play back in realtime: Player moves backwards 20 units during this time Enemy 1 revives at frame 50 Bullet reappears at frame 50 Bullet moves backwards 5 and disappears (50-45) Enemy moves left 10 (40-30) Enemy removed at frame 20.

Just looking at movement I had some ideas about how to achieve this, I thought of having a interface that changed behavior for when time was advancing or reversing. Instead of doing something like this:

```
void update()
{
    movement += new Vector(0,5);
}

```

I would do something like this:

```
public interface movement()
{
    public void move(Vector v, Entity e);
}

public class advance() implements movement
{
    public void move(Vector v, Entity e)
    {
            e.location += v;
    }
}

public class reverse() implements movement
{
    public void move(Vector v, Entity e)
    {
        e.location -= v;
    }
}

public void update()
{
    moveLogic.move(new vector(5,0));
}

```

However I realised this would not be optimal performance wise and would quickly become complicated for more advance actions (such as smooth movement along curved paths e.t.c.).

# Answer
**You might want to take a look at the Command pattern.**

Basically every reversible action your entities take are implemented as a command object. All of those objects implement at least 2 methods: Execute() and Undo(), plus whatever else you need, like a time stamp property for correct timing.

Whenever your entity performs a reversible action, you create an appropriate command object first. You save it on an Undo stack, then feed into your game engine and execute it. When you want to reverse time, you pop actions from the top of the stack and call their Undo() method, which does the opposite of the Execute() method. For example, in case of a jump from point A to point B, you perform a jump from B to A.

After you popped an action, save it on a Redo stack if you want to go forwards and backwards at will, just like the undo/redo function in a text editor or paint program. Of course, your animations must also support a "rewind" mode for playing them backwards.

For more game design shenanigans, let every entity store its actions on its own stack, so you can undo/redo them independently of each other.

A command pattern has other advantages: For example, it's pretty much trivial to build a replay recorder, since you merely need to save all the objects on the stacks to a file, and at replay time, just feed it into the game engine one by one.
> 9 votes

# Answer
You could take a look at the Memento Pattern; its primary intention is to implement undo/redo operations by rolling back object state, but for certain kinds of games it should suffice.

For a game in a real-time loop you could consider each frame of your operations as a state change and store it. This is a simple approach to implement. The alternative is to trap when an object's state is changed. For example, detecting when the forces acting upon a rigid body are changed. If you are using properties to get and set variables, this can also be a relatively straight forward implementation, the difficult part is identifying when to roll back the state, as this won't be the same time for every object (you could store the rollback time as a frame count from the start of the system).
> 1 votes

# Answer
In your particular case handling the rollback by rewinding the motion should work fine. If you are using any form of pathfinding with the AI units, just be sure to recalculate it after the rollback to avoid overlapping units.

The problem is the way you are handling the movement itself: A decent physics engine (a 2D top down shooter will be fine with a very simple one) that keeps track of past-steps info (including position, net force, etc) will provide a solid base. Then, deciding a maximum rollback and a granularity for the rollback-steps you should get the result you want.
> 0 votes

# Answer
While this is an interesting idea. I would advise against it.

Replaying the game forwards works fine, because an operation will always have the same effect on the game state. This doesn't imply that the reverse operation gives you the original state. For example, evaluate the following expression in any programming language (turn optimization off)

```
(1.1 + 3 - 3) == 1.1

```

In C and C++ at least, it returns false. While the difference may be small, imagine how much errors can accumulate at 60fps over 10s of seconds of minutes. There will be cases where a player only just misses something, but hits it while the game is replayed backwards.

I would recommend storing keyframes every half second. This won't take up too much memory. You can then either interpolate between keyframes, or even better, simulate the time between two keyframes, and then replay it backwards.

If your game isn't too complicated, just store keyframes of the game state 30 times a second and play that backwards. If you had 15 objects each with a 2D position, it would take a good 1.5 minutes to get up to a MB, without compression. Computers have gigabytes of memory.

So don't overcomplicate it, it won't be easy to replay a game backwards, and it will cause a lot of errors.
> 0 votes

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


# Question
Title: What constraint (if any) limits crowd animation variety?
I have recently noticed something in a large number of sports games relating to the animation of the crowd.

**Scenario**

Player holes the golf ball and the crowd all clap their hands. Whilst the faces and attire of the crowd members are different the animation is exactly the same. That is, the arm and hand movement of each member is identical.

Similar scenarios exist in other sports games; in football games the crowd often stand up and sit down together as well as doing things like "fist pump", wave, etc. in a perfectly synchronised manner.

**Question**

Why is there no (or very little) variation in the crowd animation? Is this a memory constraint? If so, what is the general architecure/design of this functionality and why is it so constrained? Is it along the lines of "It is more efficient to animate a collection of objects than multiple individuals"?

Or do game developers simply not see crowd variation as an important enough requirement?

As technology and game "realism" advances so quickly, this is something that still strikes me as "wooden" and unrealistic.

# Answer
Primarily this is a memory constraint. Animation is data is fairly large and often those crowd animations are considered low priority compared to what is actually going on in the game.

I would say they are all playing the same animation simply because the designers didn't want to use more ram on animation variants. ie, the actual key frame data.

Whats more, for every large crowds, a few games I know use special technology to render the same characters over and over into the scene, adjusting the camera each time to correct the perspective. ie. you are literally seeing the same characters over and over, just from a sightly different angle.

I would love to hear from a coder who had actually implemented one of these systems. I only have a fairly high level producers perspective.
> 6 votes

# Answer
I'll dissent from Jay Kyburz slightly and say that in my experience animation data is actually relatively small, but it can be expensive to compute from frame to frame. So it might be the case that they compute it once and apply it to several characters at once to save on CPU usage.
> 2 votes

# Answer
I'd suggest time and resources as another potential constraint. Given a ship date, you get to choose which is the most productive use of the time and resources you have: improving ball physics, adding extra maps, adding extra gameplay modes, or devising a more complex crowd animation system. The latter seems to be the most likely candidate for "first feature to be cut".
> 1 votes

---
Tags: animation
---


# Question
Title: Texture displays on Android emulator but not on device
I have written a simple UI which takes an image (256x256) and maps it to a rectangle. This works perfectly on the emulator however on the phone the texture does not show, I see only a white rectangle. This is my code:

```
public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
    byteBuffer = ByteBuffer.allocateDirect(shape.length * 4);
    byteBuffer.order(ByteOrder.nativeOrder());
    vertexBuffer = byteBuffer.asFloatBuffer();
    vertexBuffer.put(cardshape);
    vertexBuffer.position(0);

    byteBuffer = ByteBuffer.allocateDirect(shape.length * 4);
    byteBuffer.order(ByteOrder.nativeOrder());
    textureBuffer = byteBuffer.asFloatBuffer();
    textureBuffer.put(textureshape);
    textureBuffer.position(0);

    // Set the background color to black ( rgba ).
    gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
    // Enable Smooth Shading, default not really needed.
    gl.glShadeModel(GL10.GL_SMOOTH);
    // Depth buffer setup.
    gl.glClearDepthf(1.0f);
    // Enables depth testing.
    gl.glEnable(GL10.GL_DEPTH_TEST);
    // The type of depth testing to do.
    gl.glDepthFunc(GL10.GL_LEQUAL);
    // Really nice perspective calculations.
    gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);

    gl.glEnable(GL10.GL_TEXTURE_2D);
    loadGLTexture(gl);
}

public void onDrawFrame(GL10 gl) {
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    gl.glDisable(GL10.GL_DEPTH_TEST);
    gl.glMatrixMode(GL10.GL_PROJECTION); // Select Projection
    gl.glPushMatrix(); // Push The Matrix
    gl.glLoadIdentity(); // Reset The Matrix
    gl.glOrthof(0f, 480f, 0f, 800f, -1f, 1f);
    gl.glMatrixMode(GL10.GL_MODELVIEW); // Select Modelview Matrix
    gl.glPushMatrix(); // Push The Matrix
    gl.glLoadIdentity(); // Reset The Matrix

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

    gl.glLoadIdentity();
    gl.glTranslatef(card.x, card.y, 0.0f);
    gl.glBindTexture(GL10.GL_TEXTURE_2D, texture[0]); //activates texture to be used now
    gl.glVertexPointer(2, GL10.GL_FLOAT, 0, vertexBuffer);
    gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);
    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}

public void onSurfaceChanged(GL10 gl, int width, int height) {
    // Sets the current view port to the new size.
    gl.glViewport(0, 0, width, height);
    // Select the projection matrix
    gl.glMatrixMode(GL10.GL_PROJECTION);
    // Reset the projection matrix
    gl.glLoadIdentity();
    // Calculate the aspect ratio of the window
    GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f,
            100.0f);
    // Select the modelview matrix
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    // Reset the modelview matrix
    gl.glLoadIdentity();
}

public int[] texture = new int[1];

public void loadGLTexture(GL10 gl) {
    // loading texture
    Bitmap bitmap;
        bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.image);
        // generate one texture pointer
        gl.glGenTextures(0, texture, 0); //adds texture id to texture array
        // ...and bind it to our array
        gl.glBindTexture(GL10.GL_TEXTURE_2D, texture[0]); //activates texture to be used now
        // create nearest filtered texture
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
        // Use Android GLUtils to specify a two-dimensional texture image from our bitmap
        GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
        // Clean up
        bitmap.recycle();
}

```

As per many other similar issues and resolutions on the web i have tried setting the minsdkversion is 3, loading the bitmap via an input stream bitmap = BitmapFactory.decodeStream(is), setting BitmapFactory.Options.inScaled to false, putting the images in the nodpi folder and putting them in the raw folder.. all of which didn't help.

I'm not really sure what else to try..

# Answer
> 1 votes
Well, it happened to me once. It worked fine on the emulator, but on device, it just crashed or showed without texture. Here's the solution on StackOverflow.

### Edit:

Well, I just saw your question's about 2D, and you're using Perspective to create your viewport, consider changing it to glOrtho.

Also does your mobile use a PowerVR as GPU (Milestone mobiles, etc.)? Mine was, And I've heard out there that the RGB565 configuration is the problem here. It's a good guess. Try changing it too.

---
Tags: opengl, 2d, android, textures, opengl-es
---


title: Open GL ES 2.0 with Android

text:
# Question
Title: Open GL ES 2.0 with Android
I was wondering if someone could recommended a book that covers both android game developement and OpenGL ES 2.0. I have found some books with OpenGL 1.0, but I have heard that the syntax for OpenGL es 2.0 is totally different.

# Answer
> 1 votes
I think you don't need any book for OpenGL ES 2.0, everything is in the web ;)

I started with All about OpenGL ES 2.x, and I looked into sources of samples in Android NDK. You can also look into Maemo examples. Khronos offers an OpenGL ES 2.0 quick syntax reference.

# Answer
> 2 votes
I remember Beginning Android Games and Pro Android Games as books with good explanations on Game programming on Android and OpenGL ES.

# Answer
> 0 votes
I'm not sure if this will work for you, but I find this book very good OpenGL® ES 2.0 Programming Guide. The books explains how OpenGL ES 2.0 works and gives a lot of code examples in C language. If you know basics of it, then you should have no big problems of translating them to Java code.

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


# Question
Title: most efficient way to create a grid system in unity
I'm creating a little tower defence game to get myself acquainted with unity.

At first I was going to emulate a grid system by capturing touches / mouse clicks and rounding the coordinates to the nearest whole numbers. This is very low cost and works well for placing things, however I'm a bit of an AI geek and I've decided to make a more tangible grid so that the agents can run searches on it for pathfinding.

For this I'll need a grid of nodes and for those nodes to have a bit of information attached. Would it be a much better idea to do this entirely in code? Or could I get away with placing actual cubes in a big grid on the map?

This would certainly be easy as then I could ray cast against them - but I've tried this and rendering that many cubes slows down the game a lot!

I suppose my question is - is it unnecessarily expensive to have a load of cubes set up like this, but not rendered? Or should the cost of having a load of cube shaped collision volumes be only marginally more expensive than emulating this in code? (if at all...)

Also as a side question - should I be able to render say, 200 cubes and have a smooth game? Am I missing some instancing options? I presumed things would be automatically instanced.

# Answer
> 6 votes
I am going to attack your question out of order, partly because I am seeing issues with the way I think you're attacking the problem.

> This \[cubes\] would certainly be easy as then I could ray cast against them - but I've tried this and rendering that many cubes slows down the game a lot!

I don't know why this would be slow, unless you are constantly creating, altering, and destroying these cubes at run-time, but even then, 200 cubes is child's play to unity (when you start getting to say 10,000 simultaneously interacting items then Unity can start to have problems.

You don't need to have physical "objects" in your world to ray-cast between them. You simply need to have objects in your world (Empty GameObjects)

> I suppose my question is - is it unnecessarily expensive to have a load of cubes set up like this, but not rendered? Or should the cost of having a load of cube shaped collision volumes be only marginally more expensive than emulating this in code? (if at all...)

200 cubes (even 200 RigidBodies) is not that much in Unity. The part about emulating in code depends on what you absolutely need your nodes to know.

> Also as a side question - should I be able to render say, 200 cubes and have a smooth game? Am I missing some instancing options? I presumed things would be automatically instanced.

Instancing in Unity is based around the prefab system (basically make up your thing then create a prefab and then use it again and again in your game/scenes)

> At first I was going to emulate a grid system by capturing touches / mouse clicks and rounding the coordinates to the nearest whole numbers. This is very low cost and works well for placing things, however I'm a bit of an AI geek and I've decided to make a more tangible grid so that the agents can run searches on it for pathfinding.

if you can mask your entire game level/scene in a fixed grid you should in theory be able to use standard grid traversal, but all of your book keeping will probably need to be specificly value centric, and in the end run this is not going to be very clean/efficient.

> For this I'll need a grid of nodes and for those nodes to have a bit of information attached. Would it be a much better idea to do this entirely in code?

yes, no, maybe it depends on what information you absolutely **need** your nodes to have (the simplest node I can think of for a tower defense game is is a point, a bool occupied, and a bool reachable)

> Or could I get away with placing actual cubes in a big grid on the map?

Why would you do this? I see no value besides having something that you can physically see in the editor, and when it comes time to run the game you wont be doing anything with these cudes as cubes, so why have them in the first place if your just going to take away their collision, and rendering. All you have left is a transform which you could have right away by having empty gameObjects.

the easiest way to do nodes in Unity is to create empty gameObjects(mainly for the position), and then give them a script for all the variables you **need**, and then put all those nodes onto their own layer.

**EDIT** (In response to request for more detail in comment):

> Isn't making a cube, and taking away its collision, and rendering the same as creating an empty gameObject?

yes, and no. yes its the same in terms of physics, and rendering, but no in terms of the engines book-keeping. every fixedUpdate (especially in non-release mode) the system takes all components that a object has, and the same for its children, and puts them to be calculated, and then if any of those are not active throws it away. so its still trying to do stuff with the inactive components its just not that much. if you multiply this enough times it can amount to maybe an extra half second per frame, but that's probably up there.

> Are empty gameObjects by default cube shaped?

No. from an application standpoint think of an empty gameObject as a modifier that is modifying something, or nothing. I can create an empty gameObject, and then move it around the world/scene, and then I can rotate it, and scale it, but if it doesn't have any children nothing happens, but the changes are recorded. then if I take, and create a sphere, and make it a child of that empty gameObject then that child will take on those modifications, and have its own values stored with respect to its parent, but in essence of physical logic that empty gameObject is nothing (no size, shape, or anything), but it does have a transform, and can receive components.

> Because if they're not the benefit of a grid of cubes would be the foundations of a navMesh.

your right to a point. when I say the word grid most people think about drawing boxes, and having all of those boxes be uniform dimensions, but when we go to put things in those boxes all we really care about is a point in space (usually the center for 3D, but for 2D sprites top left) so if we take away the boxes, and instead only keep those points in space we still have a grid, we just don't have boxes.

You can still use all your favorite pathfinding algorithms with points/nodes that you did with a grid, and more. Calculate the distance between them, and apply a weight to that distance (dijoksra, and A\*), Allow the agent to consider multiply nodes at once (fuzzy logic), track the players movements through a set grid pattern, and then give a weight to a set of rules that correspond, and then have the agent chose a response based on the highest weight (exert systems).

A grid is just a visual representation that the player may never see (unless you actually want to draw those boxes on the screen, in 2D ok, but if your in a 3D perspective that can get confusing quickly especially if the camera can rotate).

> could you explain what you mean when you said - 'but all of your book keeping will probably need to be specificly value centric, and in the end run this is not going to be very clean/efficient."

I meant having each agent have to do the same rounding that you do for your mouse clicks which is very value centric, and you end up having to do a lot of the same clean up work of hard coded values, and you get the same end run checks as when doing `if(X>300){//do something}`. but if you do just find the nodes nearest to here (its up to you if you want diagonals), and if you really wanted to you could use the same logic for mouse clicks instead of rounding values just ray-cast to find the nearest node.

---
Tags: unity
---


title: Dynamically Discovering Game Content

text:
# Question
Title: Dynamically Discovering Game Content
I am trying to determine the best way to dynamically discover new levels in my Windows Phone game. This is necessary because I will be selling some levels separately to those included with the initial game purchase. I assume that it is possible for such purchases to be automatically downloaded and merged into the same directory that contains the game itself.

All my levels are pre-processed and stored as XNBs. Ideally, I would be able to obtain an enumeration of all XNBs of a particular type (ie. `Level`) within my game directory, but I cannot find a means of doing this. Alternatively, if I could get a list of all XNB names then I could use a naming convention to identify levels. Unfortunately, I can't find a way to do that either.

Am I barking up the wrong tree here? Can anyone shed any light on how I might dynamically discover content in my game?

# Answer
It took me some searching but WP7 does not support DLC and Micro-Transactions so you can't expand your game with extra levels via the marketplace so that's why you couldn't find the functionality to browse for extra files in your game directory.

What you can do:

On WP7/XNA you have full socket access, you could put up a web service and download extra levels from there. You could even launch the browser so that people can buy stuff directly from you (read the disclaimer!). You can then store them in the app folder using the built in IsolatedStorage. You can also easily retrieve the data from there.

**BIG FAT DISCLAIMER**

I'm not sure how happy MS would be with customers paying you directly for DLC, even though they don't offer these services themselves. There are some apps that do it (the Kindle app is the best example) but they could have a private contract that doesn't apply to you. Your app could get pulled if you just launch with this functionality so contact MS so that you know what is allowed. They are usually quite helpful!
> 2 votes

---
Tags: xna, assets, windows-phone-7
---


title: HTML5 Canvas game viewport

text:
# Question
Title: HTML5 Canvas game viewport
How to create in HTML5 canvas viewport? something like for tile maps.

# Answer
> 3 votes
Taking a wild stab at what you want I will give you a few ways of doing this:

## Pure CSS way... (simplified)

HTML

```
<body><canvas>Canvas not supported</canvas></body>

```

CSS

```
html, body, canvas {
 height: 100%; width: 100%; padding: 0; margin: 0;
}

```

## The JS way

HTML

```
<body><canvas id="cvs">Canvas not supported</canvas></body>

```

JS

```
window.onload = function() {
    var cvs = document.getElementById("cvs"),
        height, width;
    this.onresize = function() {
        height = window.innerHeight, width = window.innerWidth;
        cvs.setAttribute("height", height);
        cvs.setAttribute("width", width);
    };
    this.onresize.call();
};

```

# Answer
> 1 votes
You didn't say whether you're using the 2d context or WebGL; I'll assume that you're using 2d context.

You can use the 2d context object's transformation methods to set the translation.

Normally this means that at the beginning of rendering each frame, you reset the transformation, with a call such as:

```
ctx.setTransform(1,0,0,1,0,0);

```

Then you transform based on your current viewport, such as:

```
ctx.translate(- offsetX, - offsetY);

```

This assumes that you have variables offsetX and offsetY which contain the coordinates of the top-left corner of the viewport.

Then you can just render all objects normally using "World coordinates" and have the outcome you expect.

Culling is left as an exercise for the reader :)

---
Tags: javascript, html5
---


# Question
Title: Why can't I expose a Plane variable in my unity script?
I've got a script which creates raycasts. I wanted to use the (presumably less expensive) Plane.Raycast rather than the GameObject.Collider.Raycast (because the gameobject one has a distance parameter so that's one more check)

I can expose the plane gameobject in my scene easily by simply making a public gameobject variable like this:

```
public GameObject floor;

```

however when I turn it into this:

```
public Plane floor;

```

It doesn't expose in the scene. Why is this?

# Answer
It's because the only things that show up in the inspector are serializable fields or things that you implement in `OnInspectorGUI` as a custom editor for that class.

For reference: http://unity3d.com/support/documentation/ScriptReference/SerializeField

> **Serializable types are:**
>
> * All classed inheriting from UnityEngine.Object, for example Gameobject, Commponent, MonoBehaviour, Texture2D, AnimationClip..
> * All basic data types like int, string, float, bool.
> * Some built in types like Vector2, Vector3, Vector4, Quaternion, Matrix4x4, Color, Rect, Layermask...
> * Arrays of a serializable type
> * List of a serializable type (new in Unity2.6)
> * Enums
>
> Headsup note: if you put one element in a list (or array) twice, when the list gets serialized, you'll get two copies of that element, instead of one copy being in the new list twice.

Now `Plane` is just a struct that has a `Vector3` and a `float`, so you could use those two serializable types to construct a `Plane` object at runtime if you really need to.

But my guess is that you really want to leave the serialized field as `GameObject` so you can point to the plane in the scene.
> 3 votes

---
Tags: unity
---


# Question
Title: Simple question about a cocos2d based game template
I am learning a cocos2d based Game template tutorial from here and now I am at this point of the tutorial. My question is, how can i run 30 different scenes in 30 different levels of 5 chapter? Now I am using this

```
switch (gameData.selectedLevel) {

    case 1:

    [SceneManager goChapter1Level1Scene];

    break;

    (... snip a whole lot of lines...)

    case 30:

    [SceneManager goChapter5Level6Scene];

    break;

    default: break;

}

```

in the "- (void) onPlay: (CCMenuItemImage\*) sender" method. But it work only for 6 levels scene of chapter1. Other 4 chapters levels are show as same as 1st chapter levels scene. they are not show their own level scene. can any one please teach me, how can I do this stuff using this game template?

# Answer
> 0 votes
It's a total guess here, but it seems like your calculation of selectedLevel might be wrong. How are you calculating it? Is it someting like Chapter\*Level? I would check that your not just sending level, and so when the chapter changes it fails to change.

---
Tags: cocos2d-iphone, cocos2d
---


title: AndeEngine Parallax / Sprite Depth?

text:
# Question
Title: AndeEngine Parallax / Sprite Depth?
What I'm attempting to do is create a game in which a space ship explores a large area of space. I'm randomly generating placement of planets, space stations etc. I want to use the ParallaxBackground (I actually had to find a custom implementation which supports both x and y parallax values).

When a planet is generated I create a sprite, and add a new parallax entity to the background.

My issue is that when I place the sprite, it is not being placed properly (due to the parallax calculation I'm assuming). As the player navigates further away from the origin (0,0 in world space), the offset from the position the object is supposed to appear in the background and the position in which it actually appears gets larger and larger.

Here is the code for the custom drawing of the ParallaxEntity2D:

```
public void onDraw(final GLState pGLState, final Camera pCamera, final float pParallaxValueX, final float pParallaxValueY) {
            pGLState.pushModelViewGLMatrix();
            {
                final float cameraWidth = pCamera.getWidth();
                final float cameraHeight = pCamera.getHeight();
                final float shapeWidthScaled = this.mAreaShape.getWidthScaled();
                final float shapeHeightScaled = this.mAreaShape.getHeightScaled();

                //reposition
                float baseOffsetX = (pParallaxValueX * this.mParallaxFactor);
                if (this.mRepeatX) {
                    baseOffsetX = baseOffsetX % shapeWidthScaled;
                    while(baseOffsetX > 0) {
                        baseOffsetX -= shapeWidthScaled;
                    }
                }

                float baseOffsetY = (pParallaxValueY * this.mParallaxFactor);

                if (this.mRepeatY) {
                    baseOffsetY = baseOffsetY % shapeHeightScaled;
                    while(baseOffsetY > 0) {
                        baseOffsetY -= shapeHeightScaled;
                    }
                }

                //draw
                pGLState.translateModelViewGLMatrixf(baseOffsetX, baseOffsetY, 0);

                float currentMaxX = baseOffsetX;
                float currentMaxY = baseOffsetY;

                do {
                    this.mAreaShape.onDraw(pGLState, pCamera);

                    if (this.mRepeatY) {
                        currentMaxY = baseOffsetY;
                        do {
                            pGLState.translateModelViewGLMatrixf(0, shapeHeightScaled, 0);
                            currentMaxY += shapeHeightScaled;
                            this.mAreaShape.onDraw(pGLState, pCamera);
                        } while(currentMaxY < cameraHeight);
                        pGLState.translateModelViewGLMatrixf(0, -currentMaxY + baseOffsetY, 0);
                    }
                    pGLState.translateModelViewGLMatrixf(shapeWidthScaled, 0, 0);
                    currentMaxX += shapeWidthScaled;
                } while (this.mRepeatX && currentMaxX < cameraWidth);
            }
            pGLState.popModelViewGLMatrix();
        }

```

This is far beyond my ability to understand in terms of the calculation required to figure out where in screen space the sprite needs to be placed for it to show up in the background properly. I've gotten close by hacking together some simple math, but I want this to be perfect.

I guess first I need to understand what the above onDraw code is doing exactly. Maybe there is another approach that would work better for this instance? I explored being able to use the z component on a sprite, but I couldn't get this to work with GLES2 (the example for GLES1 is here).

# Answer
I think you might have been over thinking the parallax scrolling technique. All it does is make sprites that are 'further away' move slower than those that are near and all the variables we need is a speed and an offset. The code above seems to do a lot more than that, let's look at the core of the parallax scrolling technique. You will see that what you're trying to do is quite easy:

Let's only consider the X-axis for now.

Say we want to make a planet that is quite far away, we give it a parallaxSpeed of 0.9. Now say we would like the planet to be visible when the camera is at X=30. Then we need to think of some offset to make this happen: 30\*0.9 = 27 so the offset should be 3.

Let's see if this works:

```
X=25 gives us 25.5, the planet is still a bit to the right of the screen
X=30 gives us 30, the planet is in the center of the screen
X=35 gives us 34.5, the planet is a bit to the left of the screen

```

This is what we would expect for a planet quite far away. Now we need to find an offset so that offset + speed\*cameraPosition = X. This is easy: it's the difference between the desired position and the position given by the formula without a offset. So the general method is:

```
SetAtPosition(planet, float parallaxSpeed, vector2 position)
{
    planet.OffsetX = position.X - (position.X * parallaxSpeed);
    planet.OffsetY = position.Y - (position.Y * parallaxSpeed);
    planet.parallaxSpeed = parallaxSpeed;
}

```

And the method for drawing is:

```
Draw(planet, cameraPosition)
{
    Sprite sprite;
    sprite.X = planet.OffsetX + planet.parallaxSpeed * cameraPosition.X;
    sprite.Y = planet.OffsetY + planet.parallaxSpeed * cameraPosition.Y;
    sprite.Draw();
}

```

EDIT: The actual code I used to accomplish this with the AndEngine:

```
import org.andengine.engine.camera.Camera;
import org.andengine.entity.sprite.Sprite;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.util.GLState;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

public class ParallaxSprite extends Sprite {

    private float parallaxSpeed;
    private float offsetX = 0;
    private float offsetY = 0;

    /**
     * Creates an instance of {@link ParallaxSprite}
     * @param pX
     * @param pY
     * @param parallaxSpeed
     * @param pTextureRegion
     * @param pVertexBufferObjectManager
     */
    public ParallaxSprite(float pX, float pY, float parallaxSpeed, ITextureRegion pTextureRegion, VertexBufferObjectManager pVertexBufferObjectManager) {
        super(pX, pY, pTextureRegion, pVertexBufferObjectManager);

        this.parallaxSpeed = parallaxSpeed;
        this.offsetX = pX - (pX * parallaxSpeed);
        this.offsetY = pY - (pY * parallaxSpeed);
    }

    @Override
    protected void onManagedDraw(GLState pGLState, Camera pCamera) {
        pGLState.pushModelViewGLMatrix();
        {
            final float x = this.offsetX + this.parallaxSpeed * pCamera.getXMin();
            final float y = this.offsetY + this.parallaxSpeed * pCamera.getYMin();

            pGLState.translateModelViewGLMatrixf(x, y, 0);

            /* Draw only self. */
            this.preDraw(pGLState, pCamera);
            this.draw(pGLState, pCamera);
            this.postDraw(pGLState, pCamera);
        }
        pGLState.popModelViewGLMatrix();
    }

}

```
> 3 votes

---
Tags: java, android, andengine
---


title: SDL & Windows 8 Metro WinRT

text:
# Question
Title: SDL & Windows 8 Metro WinRT
I am just beginning to dip my tow into game programming and have been reading up on SDL, SFML, OpenGL, XNA, MonoGame and of course DirectX. (Needless to say there are a lot of choices out there)

As much as I like SFMLs syntax I have chosen to read up and start with SDL as it is pretty ubiquitous and available on every platform (Windows, Linux, Mac) and also available on portable devices (Android, iOS) with the current exception of WinPhone 7

After that pre-amble here is my question.

I notice that the docs say that for the windows platform the SDL API calls through to DirectX for higher perf. ( http://www.libsdl.org/intro.en/whatplatforms.html )

Microsoft have said that for Metro Game Apps you can only use DirectX (which means no XNA, no OpenGL, no SFML, etc, etc)

My question is: If SDL just wraps DirectX calls will I (we) be able to use SDL to bring games to the new Metro WinRT environment and Windows 8 marketplace?

This would be great if possible. Additionally as WinPhone 8 is supposedly built on Win8 then this could mean SDL would be available on the win phone in the future too.

Thanks for your time in responding to this question and I look forward to hearing your response.

EDIT:

Based on DeadMG's answer I have installed Visual Studio 11 (beta) in Windows 8 Consumer Preview (CP) and went file-\>New to check project types. The project types:

"Blank Application", "Direct2D Application" and "Direct3D Application"

look of interest. I have selected "Direct2D App" but SDL generates its own window when you call: SDL\_INIT

Is it possible to link/setup the SDL window to point to the Direct2D surface in the this project?

# Answer
There is no way that Microsoft could possibly tell the difference between you calling DX directly, and calling DX through a wrapper or third party library, so it's utterly irrelevant whether you use SDL or SFML or write your own.
> 2 votes

---
Tags: directx, sdl
---


# Question
Title: Class design for instantly switching between free-roaming world to/from battle world?
I plan to have an isometric world, which can be freely roam around. However, I desire the system to instantly apply the grid onto isometric world for battling system on any random encounter. Therefore, from what I expect, I should have a class of character that can generally switch between free-roaming and battle system. However, because I am still new to game programming, I do not know how should I approach this. If I make my character class such that I could abruptly derived it into either Free-roaming or Battle system, it may sound convenient, but I will have to implement this feature for all other class too (enemy, object, etc.). If I use Interface, then I won't have flexibility to add extra function to certain special class of object (maybe boss?). Or should I have a set of hierarchy of interface to tackle this problem? If so, it would be too complicated. Therefore, any suggestion?

# Answer
Two "philosophical" points:

1. Whenever, after making a design decision, you say "I will have to implement this feature for all other class\[es\] too" it means you aren't modeling the desired behaviour in the most efficient way ("Carve nature at its joints." -- Plato). In general: Don't Repeat Yourself (DRY).
2. Don't confuse classes and objects in your code with classes of concepts and real-world objects. They are ways to organize code - to DRY - nothing more, nothing less. For a concrete example of this, see: How to avoid game objects accidentally deleting themselves in C++ (A game object's death is confused with calling `delete` on the object that represents it.)

I say "philosophical", because you will need to **ignore** the above and learn it yourself through experience, so here's my suggestion:

**Use a state machine to switch your game object's behaviours**

Your game has two states: free-roam and grid-battle. So make those two into sub-states of the "playing the game" state. See http://create.msdn.com/en-US/education/catalog/sample/game\_state\_management for an XNA-oriented approach. In free-roam you use a camera that's attached to the player character, in grid-battle you render a hex-grid and lock the camera in a fixed position for an overview of the battlefield.

For your game objects, you can reference the State design pattern, which is a more generic variant of the previous link. It enables you to change an object's behaviour depending on its state. Whenever your game's sub-state switches (from free-roam to grid-battle or vice versa), you will need to switch the relevant game objects states as well.

A possible class hierarchy is this:

* GameObject { setGridBattle() setFreeRoam() }

+ class PlayerObject { move() { this.state.move(); } }
    + class BossObject { move() { this.state.move(); } explode() { this.state.explode(); }
* interface GameObjectState

+ interface PlayerObjectState { move(); }
        - class PlayerObjectGridBattle { move() { moveOverGrid(); }
        - class PlayerObjectFreeRoam { move() { moveFreeRoam(); }
    + interface BossObjectState { move(); }
        - class BossObjectGridBattle { move() { moveOverGrid(); } explode() { boom(); } }
        - class BossObjectFreeRoam { move() { moveFreeRoam(); } explode() { /\* nothing happens \*/ } }

Expanding on this could have a MovingObject and a MovingObjectState, from which PlayerObject/EnemyObject and PlayerObjectState/EnemyObjectState inherit, maybe in that case EnemyObject gains a doAI() method, but the move() method from MovingObject (and MovingObjectState) is shared between PlayerObject and EnemyObject.
> 2 votes

---
Tags: xna, architecture, isometric
---


title: Monetizing an Android library?

text:
# Question
Title: Monetizing an Android library?
I'm developing a library ( i.e. a JAR file that you put into the libs folder in eclipse ) which would extend surfaceView, which other people would hopefully use to make games.

I guess the best way to make any money off it would be to show banners on that surfaceview, right?

Maybe someone had similar experience? What advertising company would you suggest? admob, leadbolt? would they agree that I would integrate their sdk into my library ( not a finished app )?

Thanks!

# Answer
> 1 votes
I wouldn't go with ads, personally. I would go with something like a subscription model (like what Corona SDK uses). Something like: this library is for $5/month. If you subscribe, great, you get access to the latest and greatest JARs (updated monthly). If not, no worries, you can use your hoary old version forever.

---
Tags: android
---


# Question
Title: Tile walking algorithm for already known set of walkable tile?
Suppose I already have a list of tile that specify which tile the character can move to, and these tiles are clustered around the character. If I want to produce a path (maybe not shortest, but just a short path) to the desired tile, how would I construct it with the given list of tiles? I was going to do an A\* algorithm, however, thinking again, it will complicate my coding process. Therefore, is there a better way to find short path for known list of movable tile?

# Answer
What you are looking for is in the domain of Graph Theory.

Firstly, I would make sure you have a solid understanding of how the depth-first search and breadth-first search work. Knowing how these algorithms, which means being able to work through a graph by hand. I came upon this page, which seemed to fit the bill for learning how the searches work.

From there it is time to move on to Dijkstra's algorithm, which improves on the earlier searches.

Once you have a thorough grasp of Dijkstra's algorithm, you will want to learn what a heuristic is. On that Wikipedia page only the first paragraph is necessary to read, the rest is a bonus.

As an aside: Alpha-beta pruning is mentioned on the heuristic page. AB pruning is an extension on the minimax algorithm. Both of these are a natural move forwards from searches, and the more basic graph theory, starting with minimax (mostly this)

From the basic heuristic, you will want to learn about admissible heuristics. This is the crucial concept, which, when applied to Dijkstra's algorithm, gives us your final answer: the A\* search algorithm.

The A\* algorithm is quite simple once you have the knowledge background.
> 3 votes

# Answer
Amit's A\* : http://theory.stanford.edu/~amitp/GameProgramming/ , a great illustrated intro.
> 1 votes

---
Tags: path-finding, isometric
---


# Question
Title: Can glTexImage2D() use an already existing memory block?
Can I use `glTexImage2D()` and / or `glTexSubImage2D()` (or maybe there's some other method I don't know about) with an already existing block of memory, instead of always uploading the changed pixels? I already have the changed pixels somewhere in memory, and I'd like to send a pointer to that location if possible.

The problem is that I'm likely going to update a large amount of pixels, and uploading all of them introduces a lot of overhead and wasted memory. And since the application will only run on a mobile device without dedicated GPU memory, all I'm doing now is copying a big chunk of memory to another location of the same memory...

Also, I'm looking for a solution that would work on iOS devices, since the application will only run on iOS.

# Answer
Yes, you can. But not with glTexImage2D, as the just uploads image data to the gpu.

What you can do however, is by binding the texture to a pixel buffer, and then mapping the pixel buffer to memory by using glMapBuffer(GL\_PIXEL\_UNPACK\_BUFFER\_ARB, ID).

This will give you a point to the pixel data.
> 3 votes

---
Tags: ios, performance, opengl-es, memory-efficiency
---


# Question
Title: How to display image in second layer in Cocos2d
I am very new at Cocos2d and is testing to displaying an image over the "Hello World" text on a second layer and need help to get it work. I guess it is some basic stuff here and appreciate any tips etc. with this.

I know that if i put the display-code (myLayer1) in the "init" it work or do the call \[self goHere\] from the "init" in myLayer1 it works but i want to call the "goHere" directly.

I have the following code:

HelloWorld.m:

```
#import "HelloWorldLayer.h"
#import "myLayer1.h"

// HelloWorldLayer implementation
@implementation HelloWorldLayer

+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];

// 'layer' is an autorelease object.
HelloWorldLayer *layer = [HelloWorldLayer node];
myLayer1 *layer1 = [myLayer1 node];

// add layer as a child to scene
[scene addChild: layer];
[scene addChild: layer1];

// return the scene
return scene;
}

// on "init" you need to initialize your instance
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init])) {

    // create and initialize a Label
    CCLabelTTF *label = [CCLabelTTF labelWithString:@"Hello World" fontName:@"Marker Felt" fontSize:64];

    // ask director the the window size
    CGSize size = [[CCDirector sharedDirector] winSize];

    // position the label on the center of the screen
    label.position =  ccp( size.width /2 , size.height/2 );

    // add the label as a child to this Layer
    [self addChild: label];

    myLayer1 *a1 = [myLayer1 new];
    [a1 goHere];
    [myLayer1 release];

}
return self;
}

```

myLayer1.m:

```
#import "myLayer1.h"

@implementation myLayer1

-(void)goHere {

NSLog(@">>>>goHere<<<<");

CGSize size = [[CCDirector sharedDirector] winSize];

CCSprite *vv = [CCSprite spriteWithFile:@"hand.png"];
vv.position =  ccp( size.width /2 , size.height/2 );
[self addChild:vv z:3];
}

-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init])) {

}

return self;
}

@end

```

# Answer
I am not sure what are your intentions for adding a ccsprite on different layer is, but you can have the reference of the layer in your ccscene class and then add the ccsprite on the go to that reference.

But if you dont want to have an instance of that object in your ccscene class then you can get the reference to that layer by adding the tag and then get the layer with tag when ever you want to add any node to that layer.

The procedure is simple.

```
myLayer1 *a1 = [myLayer1 new];
a1.tag = 300;
[self addChild:a1];
[a1 release];

//some other function
myLayer1 *a1 = (myLayer1 *)[self getChildByTag:300];
[a1 goHere];

```

PS. also there are some problems with your code, you might want to dig into that.
> 1 votes

# Answer
These lines of code are wrong:

```
 myLayer1 *a1 = [myLayer1 new];
[a1 goHere];
[myLayer1 release];

```

for many reasons. First of all you have already instantiated a myLayer1 object in the scene static method (notice that the node method is equivalent to an alloc plus init invokation returning an autorelease pointer). Moreover you are not adding a1 instance to any parent object so its content won't be depicted. Finally you are releasing a class no the instance.

What you should do is to go in the HelloWorldLayer.h and put there the myLayer1 declaration as a class attribute

```
myLayer1 *layer1;

```

then in the HelloWorldLayer.m scene method you just have to instantiate it this way:

```
layer1 = [myLayer1 node];
[scene addChild:layer1];

```

then in the HelloWorldLayer.m init method you can invoke its method goHere

```
[layer1 goHere];

```
> 1 votes

---
Tags: multiplayer, cocos2d-iphone
---


# Question
Title: Destroying instantiated objects stored in a list not working in Unity
I have a GameObject with associated a javascript. I have defined a private variable like this:

```
    private var objects = new Array();

```

now in the Update method I instantiate new objects and push each obtained reference into the private array like this

```
    objects.push(newObjectInstance);

```

when a certain event occurs (i.e. the user press a button in the GUI) I'd like all the objects to be destroyed. I am doing that like this

```
    for (var i =0 ;i<objects.length; i++){
        Destory(objects[i]);
    }
    objects.clear();

```

The problem is that although the objects are removed from the array they remain displayed in the Game. What am I doing wrong?

# Answer
My guess is that javascript typing is messing you up.

Where is `newObjectInstance` created? Are you explicitly declaring its type to be `GameObject`? (You'd do this by doing `var newObjectInstance : GameObject = Instantiate(...);` By default the return type of `Instantiate` is `Object` and I'm not entirely sure what happens when you try to `Destroy` it.

Keep in mind that `Destroy` works on components as well as game objects, so you might be destroying something that's part of the game object but not the game object itself.

Alternatively, try changing your destroy call to `Destroy(objects[i].gameObject);` to explicitly point to the GameObject itself.
> 2 votes

# Answer
Okay I personally don't know too much about javascript as I personally always code in C# instead. A little check list for you:

1. Make sure what you push into the array is actually GameObjects and not just components
2. As Tetrad mentioned, try calling object\[i\].gameObject, just to make sure it is actual GameObjects you try to destroy
3. For debugging try to print(object\[i\]) to see if it is actual GameObjects

(Note: You mispelled --\> Destory \<--(objects\[i\]); - Maybe an issue if you copy + pasted your code)
> 1 votes

---
Tags: unity
---


# Question
Title: Winning isn't everything (organic Hierarchy)
Suppose that you have a simple online browser based game\* in which the characters are all landed nobles - Barons.

When the game starts all players are on relatively equal footing.

There is a game mechanic that allows players to swear fealty to another player. However, it's easy to assume that no amount of asking nicely will get another human player to swear fealty to you, especially since he/she theoretically has just as much muscle as you do.

So: war.

If you go to war with someone because you want them to be your vassal, what happens - realistically?

1. You defeat them, and they acknowledge your superiority and swear fealty.
2. They send you rage filled notes and continue to stubbornly resist, despite having no strength remaining to challenge you.
3. Ragequit.
4. Due to a coded mechanic, when their armies are defeated, they auto-vassal to you, and then ragequit.

My goal at this point is somewhat experimental: Can players create an organic hierarchy? Could a bunch of players haggle and battle and create a pecking order - whether stable or constantly shaken up?

\*browser based game: more a PHP based role playing game with some management and activity actions, not a clickfest flash game.

# Answer
Jeremy,

My game Neptune's Pride is a super simple space strategy game.

The object of the game is capture half of all the stars in the Galaxy so you have to wage war on your neighbors to capture them.

The game gets interesting when you realize you aren't going to be able to take on all the other players without allies. You'll need friends to trade tech with and watch your back.

An organic hierarchy forms, as you put it, as players make and break alliances, attempting to hold onto that number one spot.

There is a lot of ragequiting in NP.
> 3 votes

---
Tags: game-design, behavior
---


title: Geometry shader questions?

text:
# Question
Title: Geometry shader questions?
I had some questions on geometry shaders.

Do directx geometry shaders offer anything over the opengl ones?

What advantages does the official geometry shader implementation on opengl 3.2 have over the plug-in for 2.0? Is the official one faster?

What are the oldest cards which support opengl 3.2 and the geometry shaders on there?

What are the oldest cards which support opengl 2.0 and the geometry shader plugin?

# Answer
> Do directx geometry shaders offer anything over the opengl ones?

No.

> What are the oldest cards which support opengl 3.2 and the geometry shaders on there?
>
> What are the oldest cards which support opengl 2.0 and the geometry shader plugin?

Geometry shaders are geometry shaders, regardless of the API you use to access them. They are supported on the same class of hardware: DX10-class hardware.

> What advantages does the official geometry shader implementation on opengl 3.2 have over the plug-in for 2.0? Is the official one faster?

The core 3.2 version is not "faster". It's simply a more intuitive API.

For example, core 3.2 it doesn't use the tortured `varying in` and `varying out` syntax. It also requires you to specify the input and output primitive types directly in the shader, rather than forcing you to use pre-link program parameters. Also, you can use interface blocks to group inputs and outputs together, which makes talking about them much easier.

The only downside really is that you can't use it with removed primitive types (`GL_QUADS`, etc).
> 2 votes

---
Tags: opengl, shaders, geometry-shader
---


# Question
Title: Ball Physics : Smoothing the final bounces as the ball comes to rest
I've come against another issue in my little bouncing ball game.

My ball is bouncing around fine except for the last moments when it is about to come to rest. The movement of the ball is smooth for the main part but, towards the end, the ball jerks for a while as it settles on the bottom of the screen.

I can understand why this is happening but I can't seem to smooth it.

I'd be grateful for any advice that can be offered.

My update code is:

```
public void Update()
    {
        // Apply gravity if we're not already on the ground
        if(Position.Y < GraphicsViewport.Height - Texture.Height)
        {
            Velocity += Physics.Gravity.Force;
        }
        Velocity *= Physics.Air.Resistance;
        Position += Velocity;

        if (Position.X < 0 || Position.X > GraphicsViewport.Width - Texture.Width)
        {
            // We've hit a vertical (side) boundary
            // Apply friction
            Velocity *= Physics.Surfaces.Concrete;

            // Invert velocity
            Velocity.X = -Velocity.X;
            Position.X = Position.X + Velocity.X;
        }

        if (Position.Y < 0 || Position.Y > GraphicsViewport.Height - Texture.Height)
        {
            // We've hit a horizontal boundary
            // Apply friction
            Velocity *= Physics.Surfaces.Grass;

            // Invert Velocity
            Velocity.Y = -Velocity.Y;
            Position.Y = Position.Y + Velocity.Y;
        }
    }

```

Perhaps I should also point out that `Gravity`, `Resistance` `Grass` and `Concrete` are all of the type `Vector2`.

# Answer
Here a the steps required for improving your physics simulation loop.

### 1. Timestep

The main problem I can see with your code is that it does not account for the physics step time. It should be obvious that there is something wrong with `Position += Velocity;` because the units do not match. Either `Velocity` is actually not a velocity, or something is missing.

Even if your velocity and gravity values are scaled such that each frame happens at a time unit `1` (meaning that *eg.* `Velocity` actually means the *distance* traveled in one second), **time must appear somewhere** in your code, either **implicitly** (by fixing the variables so that their names reflect what they really store) or **explicitly** (by introducing a timestep). I believe the easiest thing to do is to declare the time unit:

```
float TimeStep = 1.0;

```

And use that value everywhere it is needed:

```
Velocity += Physics.Gravity.Force * TimeStep;
Position += Velocity * TimeStep;
...

```

Note that any decent compiler will simplify away the multiplications by `1.0`, so that part will not make things slower.

Now `Position += Velocity * TimeStep` is still not quite exact (see this question to understand why) but it will probably do for now.

Also, this needs to take time into account:

```
Velocity *= Physics.Air.Resistance;

```

It is a bit trickier to fix; one possible way is:

```
Velocity -= Vector2(Math.Pow(Physics.Air.Resistance.X, TimeStep),
                    Math.Pow(Physics.Air.Resistance.Y, TimeStep))
          * Velocity;

```

### 2. Double updates

Now check what you do when bouncing (only relevant code shown):

```
Position += Velocity * TimeStep;
if (Position.Y < 0)
{
    Velocity.Y = -Velocity.Y * Physics.Surfaces.Grass;
    Position.Y = Position.Y + Velocity.Y * TimeStep;
}

```

You can see that `TimeStep` is used twice during the bounce. This is basically giving the ball twice as much time to update itself. This is what should happen instead:

```
Position += Velocity * TimeStep;
if (Position.Y < 0)
{
    /* First, stop at Y = 0 and count how much time is left */
    float RemainingTime = -Position.Y / Velocity.Y;
    Position.Y = 0;

    /* Then, start from Y = 0 and only use how much time was left */
    Velocity.Y = -Velocity.Y * Physics.Surfaces.Grass;
    Position.Y = Velocity.Y * RemainingTime;
}

```

### 3. Gravity

Check this part of the code now:

```
if(Position.Y < GraphicsViewport.Height - Texture.Height)
{
    Velocity += Physics.Gravity.Force * TimeStep;
}

```

You add gravity for the whole duration of the frame. But what if the ball actually bounces during that frame? Then velocity will be inverted, but the gravity that was added will then make the ball accelerate away from the ground! So **excess gravity will have to be removed when bouncing**, then re-added in the correct direction.

It may happen that even re-adding gravity in the correct direction will cause velocity to accelerate too much. To avoid this, you can either skip the gravity addition (after all, it's not that much and it only lasts a frame) or clamp velocity to zero.

### 4. Fixed code

And here is the fully updated code:

```
public void Update()
{
    float TimeStep = 1.0;
    Update(TimeStep);
}

public void Update(float TimeStep)
{
    float RemainingTime;

    // Apply gravity if we're not already on the ground
    if(Position.Y < GraphicsViewport.Height - Texture.Height)
    {
        Velocity += Physics.Gravity.Force * TimeStep;
    }
    Velocity -= Vector2(Math.Pow(Physics.Air.Resistance.X, RemainingTime),
                        Math.Pow(Physics.Air.Resistance.Y, RemainingTime))
              * Velocity;
    Position += Velocity * TimeStep;

    if (Position.X < 0 || Position.X > GraphicsViewport.Width - Texture.Width)
    {
        // We've hit a vertical (side) boundary
        if (Position.X < 0)
        {
            RemainingTime = -Position.X / Velocity.X;
            Position.X = 0;
        }
        else
        {
            RemainingTime = (Position.X - (GraphicsViewport.Width - Texture.Width)) / Velocity.X;
            Position.X = GraphicsViewport.Width - Texture.Width;
        }

        // Apply friction
        Velocity -= Vector2(Math.Pow(Physics.Surfaces.Concrete.X, RemainingTime),
                            Math.Pow(Physics.Surfaces.Concrete.Y, RemainingTime))
                  * Velocity;

        // Invert velocity
        Velocity.X = -Velocity.X;
        Position.X = Position.X + Velocity.X * RemainingTime;
    }

    if (Position.Y < 0 || Position.Y > GraphicsViewport.Height - Texture.Height)
    {
        // We've hit a horizontal boundary
        if (Position.Y < 0)
        {
            RemainingTime = -Position.Y / Velocity.Y;
            Position.Y = 0;
        }
        else
        {
            RemainingTime = (Position.Y - (GraphicsViewport.Height - Texture.Height)) / Velocity.Y;
            Position.Y = GraphicsViewport.Height - Texture.Height;
        }

        // Remove excess gravity
        Velocity.Y -= RemainingTime * Physics.Gravity.Force;

        // Apply friction
        Velocity -= Vector2(Math.Pow(Physics.Surfaces.Grass.X, RemainingTime),
                            Math.Pow(Physics.Surfaces.Grass.Y, RemainingTime))
                  * Velocity;

        // Invert velocity
        Velocity.Y = -Velocity.Y;

        // Re-add excess gravity
        float OldVelocityY = Velocity.Y;
        Velocity.Y += RemainingTime * Physics.Gravity.Force;
        // If velocity changed sign again, clamp it to zero
        if (Velocity.Y * OldVelocityY <= 0)
            Velocity.Y = 0;

        Position.Y = Position.Y + Velocity.Y * RemainingTime;
    }
}

```

### 5. Further additions

For even improved simulation stability, you may decide to run your physics simulation at a higher frequency. This is made **trivial** by the above changes involving `TimeStep`, because you just need to split your frame in as many chunks as you wish. For instance:

```
public void Update()
{
    float TimeStep = 1.0;
    Update(TimeStep / 4);
    Update(TimeStep / 4);
    Update(TimeStep / 4);
    Update(TimeStep / 4);
}

```
> 19 votes

# Answer
Add a check to stop the bounce, using a minimal vertical velocity. And when you get the minimal bounce, set the ball in the ground.

```
MIN_BOUNCE = <0.01 e.g>;

if( Velocity.Y < MIN_BOUNCE ){
    Velocity.Y = 0;
    Position.Y = <ground position Y>;
}

```
> 5 votes

# Answer
So, I think the problem of why this happening is that your ball is approaching a limit. Mathematically, the ball never stops on the surface, it approaches the surface.

However, your game is not using a continuous time. It is a map, which is using an approximation to the differential equation. And that approximation is not valid in this limiting situation (you can, but you would have to take smaler and smaller time steps, which I assume is not feasible.

Physically speaking, what happens is that when the ball is very close to the surface it sticks to it **if** the total force is below a given threshold.

@Zhen answer would be fine if your system is homogeneous, which is not. It has some gravity on the y axis.

So, I would say that the solution would not be that the velocity should be bellow a given threshold, but the total force applied on the ball after the update should be bellow a given threshold.

That force is the contribution of the force exerted by the wall on the ball + the gravity.

The condition should then be something like

if (newVelocity + Physics.Gravity.Force \< threshold)

notice that newVelocity.y is a positive quantity if the bounce is on the botton wall, and gravity is a negative quantity.

Also notice that newVelocity and Physics.Gravity.Force do not have the same dimensions, as you've written in

```
Velocity += Physics.Gravity.Force;

```

meaning that, like you, I'm assuming that delta\_time = 1 and ballMass = 1.

Hope this helps
> 1 votes

# Answer
You have a position update inside your collision check, it is redundant, and wrong. And it adds energy to the ball thus potentially helping it move perpetually. Along with the gravity not being applied at some frames this gives your strange movement. Remove it.

Now you may see a different issue, that the ball gets "stuck" outside the designated area, perpetually bouncing back and forth.

A simple way of solving this issue is to check that the ball moves in the correct direction before changing it.

Thus you should make:

```
if (Position.X < 0 || Position.X > GraphicsViewport.Width - Texture.Width)

```

Into:

```
if ((Position.X < 0 && Velocity.X < 0) || (Position.X > GraphicsViewport.Width - Texture.Width && Velocity.X > 0))

```

And similar for Y direction.

In order for the ball to stop nicely you need to stop the gravity at some point. Your current implementation ensures that the ball will always resurface as gravity does not brake it as long as it is underground. You should change to always applying gravity. This however leads to the ball slowly sinking into the ground after settling. A quick fix for this is, after applying gravity, if the ball is below surface level and moving downwards, stop it:

```
Velocity += Physics.Gravity.Force;
if(Position.Y > GraphicsViewport.Height - Texture.Height && Velocity.Y > 0)
{
    Velocity.Y = 0;
}

```

These changes in total should give you a decent simulation. But do note that it is still a very simple simulation.
> 1 votes

# Answer
Have a mutator method for any and all velocity changes, then within that method you can check the updated velocity to determine if it is moving slow enough to put it at rest. Most physics systems that I know of call this 'restitution'.

```
public Vector3 Velocity
{
    public get { return velocity; }
    public set
    {
        velocity = value;

        // We get the direction that gravity pulls in
        Vector3 GravityDirection = gravity;
        GravityDirection.Normalize();

        Vector3 VelocityDirection = velocity;
        VelocityDirection.Normalize();

        if ((velocity * GravityDirection).SquaredLength() < 0.25f)
        {
            velocity.Y = 0.0f;
        }
    }
}
private Vector3 velocity;

```

In the above method we limit bouncing whenever it's along the same axis as gravity.

Something else to consider would be detecting whenever a ball has collided with the ground, and if it's moving fairly slow at the time of collision, set the velocity along the axis of gravity to zero.
> 0 votes

# Answer
Another thing: You're multiplying by a friction constant. Change that--lower the friction constant but add a fixed energy absorption on a bounce. This will damp those last bounces much faster.
> 0 votes

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


title: Blending Two different animations

text:
# Question
Title: Blending Two different animations
I'm sure there are articles around on this but I'm not really sure what they are called.

animation blending tends to give me the blend between two different complete animation such as walk and run.

what I'm after is having a player with that has a walk/jump animation and a firing gun animation. Is this still animation blending?

Can anybody enlighten me to how this process could be achieved?

# Answer
> 1 votes
The process itself is rather complicated, as it involves using a lot of quaternions and matrix operations. You can't just take average of bones rotations/positions, since it would result in bizarre picture. Here's a sample code from Havok Animation component (used for blending two hkQsTransforms - universal transform class).

```
void hkQsTransform::setZero();
void hkQsTransform::blendAddMul(const hkQsTransform& other, hkSimdRealParameter weight = 1.0f );
void hkQsTransform::blendNormalize( hkSimdRealParameter totalWeight = 1.0f);

```

I believe what you want to achieve is having two animations, let's call them Move and Shoot, and being able to have player in states Move, Shoot, ShootWhileMoving. Blending of the bones will allow you to have 3 states with only 2 animations.

You might also notice, that, for example, shooting animation doesn't take legs in account - player just takes a gun and raises it, while standing still. That's what weights are for - you can just set weights on legs' bones in shooting animation to 0, and it will simplify all of the process.

As the finishing word - blending is also very useful in transition between states, for example running and standing still. It allows smooth beginning and ending, rather than characted sharply starting and stopping. Different curves can be used when transitioning, to make the transition even more smooth, or rather sharp (but still it's a transition, not complete change - at once)/

---
Tags: animation, models, blending
---


# Question
Title: How to implement physics and AoE spells in an MMO game?
I'm making a game which will be completely centered around PVP battlegrounds and arenas. Think something like WoW, but with the RPG part removed. There will just be a lobby, where you can join a battleground and fight. I plan to use WebGL with the Three.js abstraction.

So, making a game where people can just hit each other isn't my problem - I'd like to have physics play a big role. I simply don't understand how is that possible with open source clients (open source, because it's a website)!

Also, by physics I mean things like burning logs rolling over from a hill, spells that send everything flying around, possibility of dying when hit by a high-velocity object, and so on.

I seem to have only two options:

**A**, do the calculations on the server

**B**, do the calculations on the client side

With A, the problem is that I plan to use some plugins for collision detection, and I need to have all the meshes and bounding boxes to test, which I only have access to on the client side! Also, physics might be just a bit too much for my servers to handle.

The obvious problem with B is that you can never trust the client. If I depend on the client telling me that the player got hit really hard and that he did, in fact, throw the player somewhere, that's an obvious security hole. The user can make a simple script that blocks any messages with a "he got hit" header or something, and become invincible.

But, while I was writing this, I came up with a third option, which is to let the client care about others, not just about itself. This falls under the reality checking category, I believe, because if the majority says that someone got hit, and he says he didn't, I'd trust the majority... This option's flaw is that it might be a really big strain on the clients, because this will be a browser game, and my resources are limited.

# Answer
When you do AOE, you can use player-sized cylinders for AOE detection. I think Quake does it this way.

Now for the physics question.
There are several solutions I can think of:
1) Do it all server-side, use simplified meshes and bounding boxes, optimize everything.
2) Split into ranked and unranked battlegrounds (instances), and give players the ability to host their own server. Of course, ranked matches would have to be server-side.
3) Somehow authenticate the client (hard to do in JS)
> 4 votes

# Answer
You never want to do physics simulation or game play calculations on the client if at all possible, because the client is assumed to be cheating at every opportunity. Calculations should be done on the server and handed down to the client from on high, and the client should have to accept the word of the server.

That isn't to say you can't simulate physics or do calculations for the sake of smoothing out the client's view of the world, but the final say should always lie with the server.

Frankly, I would first worry about getting the game up and running in a (moderately) playable state, and then worry about the load you place on the server. If the calculations turn out to be too complex and the game starts to lag a lot, that's when I would do optimizations.
> 5 votes

---
Tags: game-design, physics, software-engineering, mmo, security
---


# Question
Title: How can i make my program use 2 windows?
I'm working in Xna 4.0 and iwant to make a program that uses the same code in 2 different windows. What i want out of this is that one player plays in one window and the other player to play in the second window.

So i have 2 different questions:

Is it possible to use 2 windows for the same program?

Is it possible for 1 window to have focus on one controller and the other window on the other?

# Answer
Xna does not work well with two active window forms running xna code at same time...

You should work with one window splitted in two viewports.

Each xbox game controller has its own index, one will be playerindex1 and the other playerindex2, this way you can identify which controller is related to a player/viewport.
> 1 votes

# Answer
What you're asking to do is possible, but the results are not necessarily pretty. Keep in mind that with Windows, you can only have one application being 'focused' on at one time. This means that your game will need to accept updates while out of focus, since both players cannot have a focused window at the same time. Generally, you want to avoid this in favor of pausing the game whenever the window handle tells it that the player had to minimize it for some reason.

What might be a better (and simpler) idea is to do traditional 'split-screen' co-op/head-to-head. Why exactly do you need two separate windows? Perhaps there is an alternative method.
> 0 votes

---
Tags: xna, windows, xbox-controller
---


# Question
Title: Parallel rendering in DirectX 9 in WPF application
I want to know if it is possible to have parallel rendering in DirectX 9.0. I am working on a WPF application which uses DirectX 9.0 for rendering. To make my application more efficient I want to have parallel rendering capability in my application if possible. When I try to render from multiple threads, it gives me an Direct3D exception. Is there any way to do this? Any ideas?

# Answer
> 3 votes
Direct3D9 does not support rendering from more than one thread at once. The best you can do is render from a non-GUI thread.

However, there *are* operations which can be done outside D3D9, for example, computing world matrices, or copying into vertex buffers, which can be parallelised. However, anything that involves calling into a D3D9 API cannot ever be multi-threaded.

---
Tags: directx9
---


title: canvas ball physics animation

text:
# Question
Title: canvas ball physics animation
I want to animate ball in html canvas like this.

```
ctx.beginPath();
ctx.arc(75, 75, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();

```

start position is left top corner and ball's maximum height position is always the same

also I don't want to use javascript physics libraries

thanks

# Answer
> 4 votes
Theres a few ways to do this. Heres one way that keeps some physics like properties to make the balls look like they are bouncing realistically

```
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
balls = [];

canvas.width = 600;
canvas.height = 400;

var ball = function(){
    this.x = Math.random()*10;
    this.y= Math.random()*400;
    this.speed =(Math.random()*10)*.1;
    this.force = -this.speed*10;
    this.curForce = this.force;
};

ball.prototype.update = function(){
    this.x +=this.speed;
    this.y += this.curForce+=0.1;

    if(this.y >= 400){
        this.curForce = this.force;
    }
};

ball.prototype.render = function(){
   ctx.beginPath();
   ctx.arc(this.x,this.y,5,0,360);
   ctx.fill();
};

function init(){
    for(var i = 0; i < 10; i++){
        balls.push(new ball());
    }
    tick();
};

function tick(){
    ctx.clearRect(0,0,600,400);
    var i = 10;
    while(i--){
       balls[i].update();
       balls[i].render();
    }

    setTimeout(tick, 10);
};

init();

```

**Live Demo 1**

And heres a second way thats even easier and probably more of what you are looking for, but has no *realistic* physic properties to it at all.

```
var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");

canvas.width = 600;
canvas.height = 200;

// Ball stuffs
var x = 0;
    y =  0,
    angle = 0;

function drawBall(){
     x+= 0.5;    // this is the speed at which the ball moves to the right
     y+= Math.sin(angle);
     angle+=0.008; // To get exactly what you want play with this line

     ctx.clearRect(0,0,600,400);
     ctx.beginPath();
     ctx.arc(x,y,5,0,360);
     ctx.fill();

    if(y>=canvas.height){
      angle = -angle; // if the ball hits the bottom of the canvas reverse the angle.
    }
    setTimeout(drawBall, 10);
}

drawBall();

```

**Live Demo 2**

# Answer
> 2 votes
There are two ways to do this, one is to do it using an image, and the other is to do it as you have started here, drawing the ball bouncing.

If you want to draw it, you will need an animation loop. In the loop you need to update the position of the ball, clear the contents of the canvas, and draw the ball in its position, and then repeat.

Your moving from left to right, so that should be at a constant rate, and then your bouncing. the basic way to bounce would be to use a sin() function to determine the position of the ball, when you reach the bottom you need to adjust to flip the arc so that it goes back up instead of continuing, a \*-1 works, or the inverse of sin.

Lastly, if you want it to be realistic, you will need to ease the ball up and down, using an easing function. Check this link out for the easing function. http://jstween.sourceforge.net/moveSquare.html

---
Tags: javascript, html5, animation, html-canvas, 2d
---