# Question
Title: Implementing unlockable items on Android
I know this would be a beginners question (some of you might think) but I would like to know different approaches for this.

I have a game with lets say 20 unlockable items, at the main menu I have a button where the user can go to an activity and view the unlockable items. So I would like for it to have a "Locked image" and under it a text telling you what the item is and maybe how to unlock it.

What is the best way of going about this?

And then when the item is unlocked during the game, maybe put a variable in the shared preference and check at the beginning of the activity with the unlockabled items.

Let me know what you guys think. Thanks.

# Answer
> 2 votes
Knytt Stories and Spelunky do this:

They store records and unlockables in an *unencrypted* text file. To prevent curious people (who like to read random text files) from accidentally spoiling the game for themselves, it only adds things to the text file once the player encounters them. The file has lines such as `SpidersKilled=2`, but only if the player has already killed a *Spider*. The line not existing means as if it had said `SpidersKilled=0`.

This makes it possible for players who want to cheat to do so, but protects innocent curious cats from getting their tails burnt.

# Answer
> -1 votes
> **Disclaimer:** I don't have any experience in doing this, but intuitively, this is how I would consider doing it.

Firstly, in regard to @SpoonThumb's comment, I'd include the unlockable items in the game from the start.

Secondly, I'd store which items they'd unlocked as SharedPreferences on the phone, but with some form of encryption before they are saved. The encryption key would be inside your code, and then you may be able to obfuscate this code. It doesn't make it tamper-proof, but it would make it harder for someone who wanted to tamper with it.

You may consider storing the things they've unlocked on a server somewhere, but I get annoyed when games do this, because I can't play them properly when I am offline. Perhaps a middle ground would be to do both, and whenever they are connected to the server, just check that they haven't tampered with their unlocked items. For example, let them do whatever they want on their phone, but as soon as they try to submit a high score, perhaps you could check if the preferences on the phone are the same as those on the server.

---
Tags: android, achievements
---


# Question
Title: Using XNA ContentPipeline to export a file in a machine without full XNA GS
My game uses the Content Pipeline to load the spriteSheet at runtime. The artist for the game sends me the modified spritesheet and I do a build in my machine and send him an updated project. So I'm looking for a way to generate the xnb files in his machine (this is the output of the content pipeline) without him having to install the full XNA Game studio.

1. I don't want my artist to install VS + Xna (I know there is a free version of VS but this won't scale once we add more people to the team).
2. I'm not interested in running this editor/tool in Xbox so a Windows only solution works.
3. I'm aware of MSBuild options but they require full XNA

I researched Shawn's blog and found the option of using Msbuild Sample or a new option in XNA 4.0 that looked promising here but seems like it has the same restriction: Need to install full XNA GS because the ContentPipeline is not part of the XNA redist.

So has anyone found a workaround for this?

# Answer
> Seems like the right answer to this is to skip the ContentPipeline and use Texture2D.FromStream to load the textures at runtime. This method works fine in a PC and even though there will be a small performance hit this is something that I can optimize once I'm closer to the release date. For now, having the ability of dynamically modifying the content for both the editor and game are exactly what I need. Once the content is frozen I can optimize this by going back to the ContentPipeline.

Since you've chosen this route I must warn you that it's actually not as simple as just using `Texture2D.FromStream` for two reasons:

**Problem #1 - Lack of pre-multiplied alpha support**

XNA4 now handles textures with colors in premultiplied alpha format by default. When you load a texture through the content pipeline, that processing is done for you automatically. Unfortunately `Texture2D.FromStream` doesn't do the same thing, so any textures that require some degree of transparency will be loaded and rendered incorrectly. Below is a screenshot to illustrate the problem:

So in order to get the correct results, you need to do the processing yourself. The method I'll show uses the GPU to do the processing so it's pretty fast. It was based on this great article. Of course you could also instruct `SpriteBatch` to render in the old NonPremultiplyAlpha mode but I don't really recommend doing that.

**Problem #2 - Unsupported formats**

The content pipeline supports more formats than `Texture2D.FromStream`. In particular, `Texture2D.FromStream` only supports png, jpg and gif. On the other hand, the content pipeline supports bmp, dds, dib, hdr, jpg, pfm, png, ppm, and tga. If you try to load an usuported format through `Texture2D.FromStream` you'll get an `InvalidOperationException` with little additional information.

I really needed bmp support on my engine so for that particular case I found a workaround that seems to work okay. I don't know about any of the other formats though. The catch with my method is that you need to add a reference to the `System.Drawing` assembly to your project, because it makes use of GDI's `Image.FromStream` which supports more formats than `Texture2D.FromStream`.

If you don't care about supporting bmp you can easily drop that part of my solution and just do the pre-multiplied alpha processing.

**Solution - Simple Version (Slower)**

First of all, here's the *simplest* solution if you don't care about supporting bmps. In this example the processing stage is done entirely on the CPU. It's a bit slower than the alternative I'll show below (I did benchmark both solutions) but easier to understand:

```
public static Texture2D FromStream(GraphicsDevice graphicsDevice, Stream stream)
{
    Texture2D texture = Texture2D.FromStream(graphicsDevice, stream);
    Color[] data = new Color[texture.Width * texture.Height];
    texture.GetData(data);
    for (int i = 0; i != data.Length; ++i)
        data[i] = Color.FromNonPremultiplied(data[i].ToVector4());
    texture.SetData(data);
    return texture;
}

```

If you care about bmps then the thing you need to do is load the image with GDI first and then convert into PNG internally before passing it to `Texture2D.FromStream`. Here's the code that does that:

```
// Load image using GDI because Texture2D.FromStream doesn't support BMP
using (Image image = Image.FromStream(stream))
{
    // Now create a MemoryStream which will be passed to Texture2D after converting to PNG internally
    using (MemoryStream ms = new MemoryStream())
    {
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        ms.Seek(0, SeekOrigin.Begin);
        texture = Texture2D.FromStream(_graphicsDevice, ms);
    }
}

```

**Solution - Complex Version (Faster)**

Finally, the approach I use on my projects is to use the GPU to do the processing instead. In this method you need to create a render target, set up some blend states properly, and draw the image twice with a SpriteBatch. At the end I go over the entire RenderTarget2D and clone the contents into a separate Texture2D object because the RenderTarget2D is volatile and won't survive things like changing the backbuffer size so it's safer to make a copy.

The funny thing is that even with all of this, on my tests this approach performed about 3 times faster than the CPU approach. So it's definitively faster than going over each pixel and calculating the color yourself. The code is a bit long so I placed it in a pastebin:

http://pastie.org/3651642

Just add that class to your project, and using it as simple as:

```
TextureLoader textureLoader = new TextureLoader(GraphicsDevice);
Texture2D texture = textureLoader.FromFile("Content/texture.png");

```

*Note: You only need to create one `TextureLoader` instance for the entire game. Also I'm using the BMP fix but you can take it out if you don't need and gain a bunch of performance, or just leave the `needsBmp` parameter as false.*
> 12 votes

# Answer
I think most teams would commit the xnb changes (well, all changes really, xnb includud) to their svn server (that can be set up for free) and allow others (the artist, etc.) to update their own working copies.

In fact, that would be a good mechanism for the artist to version control the original (pre- xnb) art. He would commit changes to that, you would update your working copy of it, build it (making it an xnb in the process), commit your changes, he updates his working copy of your work and and everybody has all changes. (You have latest raw artwork, he has the xnb(s).

This scales very well too.
> 3 votes

# Answer
I kept investigating this and will post this for benefit of someone that has the same question.

Seems like the right answer to this is to skip the ContentPipeline and use Texture2D.FromStream to load the textures at runtime. This method works fine in a PC and even though there will be a small performance hit this is something that I can optimize once I'm closer to the release date.

For now, having the ability of dynamically modifying the content for both the editor and game are exactly what I need. Once the content is frozen I can optimize this by going back to the ContentPipeline.
> 1 votes

# Answer
Check this project out.

It will allow your artist to create XNB out of just about anything the default XNA content pipeline supports. The XNA framework redistributable is still necessary though your artist doesn't need Visual Studio.
> 0 votes

---
Tags: xna, xna-content-pipeline
---


title: Horizontal wrapping with AndEngine

text:
# Question
Title: Horizontal wrapping with AndEngine
How would one implement the effect of a sprite disappearing on one side of the screen and appearing on the other using AndEngine? Like in Kid Icarus, seen here at around 1:22.

# Answer
As we discussed in the comments, you don't want to draw two sprites. So we go to the shader level.

I've updated this for using with the fragment shader. You just need to pass in the screen min and max.

```
uniform int screenMax;
uniform int screenMin;

...

if(gl_FragCoord.x > screenMax) {
    gl_FragCoord.x = screenMin + (gl_FragCoord.x - screenMax);
}
if(gl_FragCoord.x < screenMin) {
    gl_FragCoord.x = screenMax + (screenMin - gl_FragCoord.x);
}

```

If you haven't done anything with shaders yet, you can read up about them here.

**EDIT**

Thinking about this more, I have no idea if it will even work. I don't know if things get culled off screen before or after this. You should test it out!
> 1 votes

# Answer
Unfortunately I've never used AndEngine before so I can't give you a specific answer to your problem, but I've asked a similar question before for XNA and got a great answer out of it. Here's a link to it:

How to create a 2D region where sprites are automatically wrapped?

That approach which uses a few render targets is great when you want wrapping to happen to *everything* in your game world automatically. That's because wrapping is done for the entire screen at once, instead of having to handle them individually for each object. Also notice that the example in that link is a lot more complicated, with complete 4-way wrapping in every direction.

But if on the other hand only your main character will be doing the wrapping, and especially since you only need horizontal wrapping, then it's probably *a lot* easier to just draw your character two times when needed on each side of the screen. For instance something like the following pseudocode:

```
// On update wrap character position
if(character.X < camera.Left)
    character.X += camera.Width;
else if(character.X > camera.Right)
    character.X -= camera.Width;

// On draw decide how many times to draw and where
DrawCharacterAt(character.X, character.Y);
if(character.Left < camera.Left)
    DrawCharacterAt(character.X + camera.Width, character.Y);
else if(character.Right > camera.Right)
    DrawCharacterAt(character.X - camera.Width, character.Y);

```

Where `X` is the center line of your character, character `Left` / `Right` are the extremities of the character sprite, and camera `Left` / `Right` are the borders of the camera in *world space* i.e. the same space as your character so that they can be compared.
> 0 votes

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


# Question
Title: How do I fix these compiler errors in Apple Crunch?
I've been looking around and I finally got the full source code for a game called *Apple-Crunch* from Google Code. But when I put it into my project, the source code included so many errors in the class files such as:

* cannot be resolved into a type
* the constructor is undefined
* the method method() is undefined for the type Sprite class.java

I downloaded the source directly from the command-line and noticed errors popping up on my project. Since I couldn't figure out how to import the actual folder into my workspace (it wouldn't show up on existing projects) I decided to copy and overwrite the folders into the project.

The errors were still there so I looked at the class files and noticed that the classes with errors extended from `RokonActivity`. I then proceeded to add to the libs folder the Rokon library in hopes to fix the errors. Sadly it didn't work and now I don't what to do to fix the errors.

How do I fix the errors without having to manually change the code? The source code should be fully functional so why are there errors?

# Answer
Send the developer a few euros (more than two) and an email asking for help setting up Eclipse with his project. Support open source and get the exact help you need. WIN-WIN.
> 3 votes

# Answer
AppleCrunch is based on Rokon which I think is not maintained anymore. Rokon is based on LibGDX which is very actively maintained. My advice is stick with LibGDX. An alternative is AndEngine but I found the lack of documentation sickening when I was a beginner so I chose LibGDX, but the choice is yours.
> 0 votes

---
Tags: android, open-source
---


# Question
Title: Physics in carrom like game using cocos2d + Box2D
I am working on carrom like game using cocos2d + Box2D. I set world gravity(0,0), want gravity in z-axis. I set following values for coin and striker body:

Coin body (circle with radius - 15/PTM\_RATIO):

```
density = 20.0f;
friction = 0.4f;
restitution = 0.6f;

```

Striker body (circle with radius - 15/PTM\_RATIO):

```
density = 25.0f;
friction = 0.6f;
restitution = 0.3f;

```

Output is not smooth. When I apply `ApplyLinearImpulse(force,position)` the coin movement looks like floating in the air - takes too much time to stop.

What values for coin and striker make it look like real carrom?

# Answer
Box2D comes with a FrictionJoint. From the docs:

> The friction joint is used for top-down friction. The joint provides 2D translational friction and angular friction.

As far as I know it doesn't really matter what you attach your physics-bodies to (using the joint). So you could attach them all to a border of the play-board and tweak the friction/torque settings until it looks realistic.
> 3 votes

# Answer
Use `setDamping`. It acts as air resistance.

```
object.setDamping(10.4);

```
> 1 votes

---
Tags: physics, box2d, cocos2d-iphone
---


title: Shadowmap granularity

text:
# Question
Title: Shadowmap granularity
I thought that we could re-use the same shadowmap for every light. But I've seen an industry article suggesting that you can't re-use shadowmaps between lights, and have to use separate surfaces.

Do we need one shadowmap per light? Or one for the whole process?

# Answer
> 5 votes
By "re-use the same shadowmap" I assume you mean re-use the memory (the render target). Obviously you can't re-use the *data* since each light has a different view of the world. :)

Anyway, yes, you can re-use the render target if you want. There are a couple of caveats. First, obviously you must design your renderer so that it only needs one shadow map at a time, which can be inconvenient or can require some changes in your pipeline. For instance, if you want to use cascaded shadow mapping for your sun light you may need a screen-space buffer to hold the shadow results, so you can accumulate multiple slices without needing to redraw your scene for each slice.

The other caveat is that you may see reduced performance, because many newer GPUs can work on multiple draw calls in parallel (even to different render targets), but this breaks if one draw call needs the result of a previous one. So if you had several shadow map render targets, the GPU might be able to parallelize (to some extent) the draw calls to draw all the shadow maps, then separately parallelize the draw calls that read the shadow maps and draw the lights. But if you have only one render target, you must serially draw shadow map A, draw light A, draw shadow map B, draw light B, etc. On high-end GPUs these operations may not saturate the GPU individually, so some cores will be left idle.

Given this, for best performance you should probably have at least two shadow map render targets and cycle through them, but it's still not obligatory to have separate render targets for each individual light. Another way is to try to provide the GPU with some other work it can use to fill the gaps---drawing particles into a separate render target, perhaps. (And as with all performance concerns, YMMV, so profile it!)

---
Tags: 3d, lighting, shadow-mapping
---


# Question
Title: How do I determine the draw order in an isometric view flash game?
This is for a flash game, with isometric view. I need to know how to sort object so that there is no need for z-buffer checking when drawing. This might seem easy but there is another restriction, a scene can have 10,000+ objects so the algorithm needs to be run in less than O(n^2). All objects are rectangular boxes, and there are 3-4 objects moving in the scene. What's the best way to do this?

**UPDATE**

in each tile there is only object (I mean objects can not stack on top of each other). and we access to both map of Objects and Objects have their own position.

**UPDATE2**

see these figures:

in first one first blue object should be drawn then green then red. while in second one you have to draw them in reverse order. you need to draw red first and then green and finally blue object. as you can see there is no difference in position of blue and red objects ,they both have different distance from camera and so on. but because of their relative position to green box, you need to change their draw order between two images. that's what makes this problem a mess.

side-note: since all objects are rectangular prism, it's mathematically provable that there is at-least one draw order to satisfy problem needs.

# Answer
> 10 votes
This is actually very simple if your objects match up with your isometric tiles. Take a look at this image:

You should first draw the object at the red position, then objects at blue, then green, then yellow, then magenta, and so on... It should be fairly obvious how to implement this if your board has objects in it instead of objects having position as an attribute. If that's not your case, you should keep a separate data structure, updating it whenever an object moves (which should be fairly easy too.)

This has a new problem: you can easily see how now its complexity is O(N) where N is your board size (`N=W*H`). To overcome this problem just create a new linear data structure where each index in your structure matches a given depth, updating it whenever an object changes depth.

The case where an object doesn't match with a single tile is a bit harder, so I will post it if you need it as soon as you update your question.

# Answer
> 2 votes
I have no special knowledge on this subject, but here's a thought.

Start by marking each cell as "not drawn". (Or, equivalently, use an array to represent the location of the closest "drawn" thing on each "near-far line" of cells, or a set, etc.) Then, for each cell (I would probably go through them in the order kaoD described): check whether that cell has been drawn; if it has not been drawn and contains an object, check whether each cell that would be obscured by that object has been drawn, and if not draw it recursively; draw the object contained by that cell if necessary; and mark that cell and any cells occupied by its object as "drawn".

I'm assuming that you can quickly map a cell to the object inside it, if any. I believe this is O(n) time, though it could end up building a large stack (which you may want to turn into a linked list if you're worried about running out of stack space).

If you really need a list, you can append to a list instead of drawing. I suspect that starting with a mostly-sorted list doesn't help.

# Answer
> 1 votes
I'd use the painter's algorithm with a taxicab distance from the furthest cell away from the camera, drawing the ones closest to the camera first and then moving outward.

Edit: This doesn't work unless you can draw the contents of each cell individually.

# Answer
> 1 votes
What makes you believe it's “mathematically provable that there is at-least one draw order to satisfy problem needs”? Here is a trivial counterexample where you cannot rely on z-sorting objects:

---
Tags: algorithm, flash, isometric, draw-order
---


# Question
Title: Why doesn't my texture display with this GLSL shader?
I am trying to display a DXT1 compressed texture on a quad using a VBO and shaders, but I have been unable to get it working. All I get is a black square.

I know my texture is uploaded properly because when I use immediate mode without shaders the texture displays fine but I will include that part just in case. Also, when I change the gl\_FragColor to something like vec4 (0.0, 1.0, 1.0, 1.0) then I get a nice blue quad so I know that my shader is able to set the colour. It appears to be either the texture is not being bound correctly in the shader or the texture coordinates are not being picked up. However, I can't find the error! What am I doing wrong?

I am using OpenTK in C# (not xna).

Vertex Shader:

```
void main() {
    gl_TexCoord[0] = gl_MultiTexCoord0;
    // Set the position of the current vertex
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}

```

Fragment Shader:

```
uniform sampler2D diffuseTexture;
void main() {
    // Set the output color of our current pixel
    gl_FragColor = texture2D(diffuseTexture, gl_TexCoord[0].st);
    //gl_FragColor = vec4 (0.0,1.0,1.0,1.0);
}

```

Drawing Code:

```
int vb, eb;
GL.GenBuffers(1, out vb);
GL.GenBuffers(1, out eb);
//                      Position        Texture
float[] verts = {   0.1f, 0.1f, 0.0f,  0.0f, 0.0f,
                    1.9f, 0.1f, 0.0f,  1.0f, 0.0f,
                    1.9f, 1.9f, 0.0f,  1.0f, 1.0f,
                    0.1f, 1.9f, 0.0f,  0.0f, 1.0f
                };
uint[] indices = {
                   0, 1, 2,
                   0, 2, 3
                 };

//upload data to the VBO
GL.BindBuffer(BufferTarget.ArrayBuffer, vb);
GL.BindBuffer(BufferTarget.ElementArrayBuffer, eb);

GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(verts.Length * sizeof(float)), verts, BufferUsageHint.StaticDraw);
GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(indices.Length * sizeof(uint)), indices, BufferUsageHint.StaticDraw);

//Upload texture
int buffer = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2D, buffer);

GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (float)TextureWrapMode.Repeat);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (float)TextureWrapMode.Repeat);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (float)TextureMagFilter.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (float)TextureMinFilter.Linear);

GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (float)TextureEnvMode.Modulate);

GL.CompressedTexImage2D(TextureTarget.Texture2D, 0, texture.format, texture.width, texture.height, 0, texture.data.Length, texture.data);

//Draw
GL.UseProgram(shaderProgram);

GL.EnableClientState(ArrayCap.VertexArray);
GL.EnableClientState(ArrayCap.TextureCoordArray);

GL.VertexPointer(3, VertexPointerType.Float, 5 * sizeof(float), 0);
GL.TexCoordPointer(2, TexCoordPointerType.Float, 5 * sizeof(float), 3);

GL.ActiveTexture(TextureUnit.Texture0);
GL.Uniform1(GL.GetUniformLocation(shaderProgram, "diffuseTexture"), 0);

GL.DrawElements(BeginMode.Triangles, indices.Length, DrawElementsType.UnsignedInt, 0);

```

# Answer
The last param to your texcoord pointer is an offset in bytes, not floats, so it's 12 (or 3 * sizeof (float) if you prefer).
> 5 votes

---
Tags: c#, textures, glsl, vbo, opentk
---


# Question
Title: How can I calculate a vertex normal for a hard edge?
Here is a picture of a lovely polygon:

Circled is a vertex, and numbered are its adjacent faces. I have calculated the normals of those faces as such (not yet normalized, 0-indexed):

```
Vertex 1 normal 0:   0.000000   0.000000    -0.250000
Vertex 1 normal 1:   0.000000   0.000000    -0.250000
Vertex 1 normal 2:  -0.250000   0.000000     0.000000
Vertex 1 normal 3:  -0.250000   0.000000     0.000000
Vertex 1 normal 4:   0.250000   0.000000     0.000000

```

What I'm wondering is, how can I determine, taken as given that I want this vertex to represent a hard edge, whether its normal should be the normal of 1/2 or 3/4? My plan after I glanced at the sketch I used to put this together was "Ha! I'll just use whichever two faces have the same normal!" and now I see that there are two sets of two faces for which this is true.

Is there a rule I can apply based on the face winding, angle of the adjacent edges, moon phase, coin flip, to consistently choose a normal direction for this box?

For the record, all of the other polygons I plan to use will have their normals dictated in Maya, but after encountering this problem, it made me really curious.

# Answer
> 9 votes
You'll need to duplicate the normal for the corner N times (where N is the number of "sides" it is shared amongst). If you try to use one value for all "sides," you'll end up averaging it, and your lighting will not appear to have that hard edge that you're looking for.

---
Tags: vector, linear-algebra, normals
---


title: Procedural Mesh: UV mapping

text:
# Question
Title: Procedural Mesh: UV mapping
I made a procedural mesh and now I want to apply a texture to it. The problem is, I cannot get it to stick the way I want it to.

The idea is to have the texture painted only once over the whole mesh, so that there is no repeating. How should I map the UV to make that happen?

My mesh is a simple plane consisting of 56 triangles. I'd add pictures to clear things up but I cannot since my reputation is below 10 points.

Any help is appreciated.

EDIT(Kind people gave me up votes, thank you):

Meet my mesh:

And when textured(tried to repeat the texture):

And my texture:

EDIT 2:

bummzack's instructions worked like a charm and the mesh got textured just as I wanted it to. Thank you.

# Answer
To map your texture once on the mesh, your UV coordinates should go from `0..1` over the whole mesh. But depending on the mesh at hand, this can get really tricky.

Since it's a plane, this should be simpler. Just look at the plane from it's "up" direction and assign `0,0` to the top left and `1,1` to bottom right. The vertices in between should be fractions. Eg. a vertex in the middle would have `0.5, 0.5` as UV coordinate.

Here's an example:

```
   0,0         0.33,0      0.66,0      1,0
 +-----------+-----------+-----------+
 |           |           |           |
 | 0,0.25    | 0.33,0.25 | 0.66,0.25 | 1,0.25
 +-----------+-----------+-----------+
 |           |           |           |
 |           |           |           |
 |           |           |           |
 |           |           |           |
 |           |           |           |
 | 0,1       | 0.33,1    | 0.66,1    | 1,1
 +-----------+-----------+-----------+

```
> 12 votes

---
Tags: unity, textures, procedural-generation, 3d-meshes, procedural
---


title: A Poker Game with XNA

text:
# Question
Title: A Poker Game with XNA
A customer of mine asked me to develop a Poker Game for him where they play poker with his friends online.

I have been looking for a good reason to start programming with XNA. Would you implement it with XNA if you were developing a game like this ?

Is there any ebook/online tutorials/video trainings which has some similar sample applications?

# Answer
> 3 votes
Doing it XNA with will give lots of flexibility with fancy animations; otherwise if you want something simpler WPF is easier. I might be biased because I've just had 8 month straight programming with WPF/WinRT. Anyhow, MS actually has sample XNA card game http://create.msdn.com/en-US/education/catalog/sample/blackjack.

I also recommend this site for tutorials: http://rbwhitaker.wikidot.com/2d-tutorials

# Answer
> 0 votes
As long as you don't want to use 3D i'd say skip XNA. Where WPF has an event driven model, XNA uses a real time loop for updates in game logic. This makes several things more complicated, for example you don't have regular buttons to post the Blinds, Bet, Call or Fold. These would be images in XNA and you need to detect user clicks on the screen and find out if this click was on an image or not.

Doesn't wpf also have a lot of animation possibilities?

---
Tags: xna, networking
---


# Question
Title: How can I apply different actions to different parts of a 2D character?
I am developing a 2D platform game in Java. The player has a gun in his hand every time. He needs to walk and shoot with the gun(arrow keys for walk and X key to shoot). The walk cycle takes 6 frames and i am able to import the sprite sheet and animate the sequence when I press arrow key. But i need to add the gun motion. The player holds the gun upwards and when X key is pressed he brings it straight and shoots. How to implement the walk + shoot action?

# Answer
> 12 votes
> The player sprite is one piece.

Then either:

1. The sprite needs to not be one piece. Split it into two sprites and render them that way. The top and bottom halves can animate independently sometimes but dependently other times. See Contra.
2. You need special frames of sprite animation for walking and shooting simultaneously.

---
Tags: 2d, animation, procedural
---


title: Can't get LWJGL lighting to work

text:
# Question
Title: Can't get LWJGL lighting to work
I'm trying to enable lighting in lwjgl according to the method described by NeHe and this post. However, no matter what I try, all faces of my shapes always receive the same amount of light, or, in the case of a spinning shape, the amount of lighting seems to oscillate. All faces are lit up by the same amount, which changes as the pyramid rotates. Concrete example (apologies for the length):

Note how all panels are always the same brightness, but the brightness varies with the pyramid's rotation.

This is using lwjgl 2.8.3 on Mac OS X.

```
package com;

import com.zarkonnen.lwjgltest.Main;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.lwjgl.util.glu.*;
import org.lwjgl.input.Keyboard;

import java.nio.FloatBuffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 *
 * @author penguin
 */
public class main {

    public static void main(String[] args) {
        try {
            Display.setDisplayMode(new DisplayMode(800, 600));
            Display.setTitle("3D Pyramid");
            Display.create();
        } catch (Exception e) {
        }
        initGL();

        float rtri = 0.0f;
        Texture texture = null;
        try {
            texture = TextureLoader.getTexture("png", Main.class.getResourceAsStream("tex.png"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        while (!Display.isCloseRequested()) {
            // Draw a Triangle :D

            GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);

            GL11.glLoadIdentity();

            GL11.glTranslatef(0.0f, 0.0f, -10.0f);

            GL11.glRotatef(rtri, 0.0f, 1.0f, 0.0f);

            texture.bind();

            GL11.glBegin(GL11.GL_TRIANGLES);

            GL11.glTexCoord2f(0.0f, 1.0f);
            GL11.glVertex3f(0.0f, 1.0f, 0.0f);
            GL11.glTexCoord2f(-1.0f, -1.0f);
            GL11.glVertex3f(-1.0f, -1.0f, 1.0f);
            GL11.glTexCoord2f(1.0f, -1.0f);
            GL11.glVertex3f(1.0f, -1.0f, 1.0f);

            GL11.glTexCoord2f(0.0f, 1.0f);
            GL11.glVertex3f(0.0f, 1.0f, 0.0f);
            GL11.glTexCoord2f(-1.0f, -1.0f);
            GL11.glVertex3f(1.0f, -1.0f, 1.0f);
            GL11.glTexCoord2f(1.0f, -1.0f);
            GL11.glVertex3f(1.0f, -1.0f, -1.0f);

            GL11.glTexCoord2f(0.0f, 1.0f);
            GL11.glVertex3f(0.0f, 1.0f, 0.0f);
            GL11.glTexCoord2f(-1.0f, -1.0f);
            GL11.glVertex3f(-1.0f, -1.0f, -1.0f);
            GL11.glTexCoord2f(1.0f, -1.0f);
            GL11.glVertex3f(1.0f, -1.0f, -1.0f);

            GL11.glTexCoord2f(0.0f, 1.0f);
            GL11.glVertex3f(0.0f, 1.0f, 0.0f);
            GL11.glTexCoord2f(-1.0f, -1.0f);
            GL11.glVertex3f(-1.0f, -1.0f, -1.0f);
            GL11.glTexCoord2f(1.0f, -1.0f);
            GL11.glVertex3f(-1.0f, -1.0f, 1.0f);

            GL11.glEnd();

            GL11.glBegin(GL11.GL_QUADS);
            GL11.glVertex3f(1.0f, -1.0f, 1.0f);
            GL11.glVertex3f(1.0f, -1.0f, -1.0f);
            GL11.glVertex3f(-1.0f, -1.0f, -1.0f);
            GL11.glVertex3f(-1.0f, -1.0f, 1.0f);
            GL11.glEnd();

            Display.update();
            rtri += 0.05f;
            // Exit-Key = ESC
            boolean exitPressed = Keyboard.isKeyDown(Keyboard.KEY_ESCAPE);
            if (exitPressed) {
                System.out.println("Escape was pressed!");
                Display.destroy();

            }
        }

        Display.destroy();
    }

    private static void initGL() {
        GL11.glEnable(GL11.GL_LIGHTING);
        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();
        GLU.gluPerspective(45.0f, ((float) 800) / ((float) 600), 0.1f, 100.0f);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);
        GL11.glLoadIdentity();

        GL11.glEnable(GL11.GL_TEXTURE_2D);
        GL11.glShadeModel(GL11.GL_SMOOTH);
        GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        GL11.glClearDepth(1.0f);
        GL11.glEnable(GL11.GL_DEPTH_TEST);
        GL11.glDepthFunc(GL11.GL_LEQUAL);
        GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST);
        float lightAmbient[] = {0.5f, 0.5f, 0.5f, 1.0f};  // Ambient Light Values
        float lightDiffuse[] = {1.0f, 1.0f, 1.0f, 1.0f};      // Diffuse Light Values
        float lightPosition[] = {0.0f, 0.0f, 2.0f, 1.0f}; // Light Position

        ByteBuffer temp = ByteBuffer.allocateDirect(16);
        temp.order(ByteOrder.nativeOrder());
        GL11.glLight(GL11.GL_LIGHT1, GL11.GL_AMBIENT, (FloatBuffer) temp.asFloatBuffer().put(lightAmbient).flip());              // Setup The Ambient Light
        GL11.glLight(GL11.GL_LIGHT1, GL11.GL_DIFFUSE, (FloatBuffer) temp.asFloatBuffer().put(lightDiffuse).flip());              // Setup The Diffuse Light
        GL11.glLight(GL11.GL_LIGHT1, GL11.GL_POSITION, (FloatBuffer) temp.asFloatBuffer().put(lightPosition).flip());         // Position The Light
        GL11.glEnable(GL11.GL_LIGHT1);                          // Enable Light One
    }
}

```

# Answer
For lighting to work, every vertex needs a normal. What seems to be the case right now is that all of your vertices have the same normal, which is why all the faces are getting the same amount of light.

To calculate the normal for a triangle, take the cross-product using two of its sides and normalize it. However, this will produce hard edges, which are not always desirable. In that case, you calculate normals per-vertex. This is done by adding all of the face normals of the triangles that share the vertex together an normalizing the vector sum.
> 4 votes

---
Tags: opengl, lighting, lwjgl, macos
---


# Question
Title: How can I clear explosions in my function?
Hi I have a function to place bombs, and a for loop that places explosions on the tiles where possible.

My problem is that I can't remove the explosions after a while. I've tried everything I can come up with so now I turn here as a last resort.

The function looks like this:

```
function Bomb(){
var placebomb = false;
    if(placeBomb && player.bombs != 0){
        map[player.Y][player.X].object = 2;
        var bombX = player.X;
        var bombY = player.Y;
        placeBomb = false;
        player.bombs--;
        setTimeout(explode, 3000);
    }
    function explode(){
    var explodeNorth = true;
    var explodeEast = true;
    var explodeSouth = true;
    var explodeWest = true;

    map[bombY][bombX].explosion = 1;
    delete map[bombY][bombX].object;

    for(i=0;i<=player.bombRadius;i++){
        if(explodeNorth && map[bombY-i][bombX]){
            if(!map[bombY-i][bombX].wall){
                if(!map[bombY-i][bombX].object){
                    map[bombY-i][bombX].explosion = 1;
                }
                else
                    var explodeNorth = false;
                    delete map[bombY-i][bombX].object;
                    map[bombY-i][bombX].explosion = 1;
            }
            else
                var explodeNorth = false;
        }

        if(explodeEast && map[bombY][bombX+i]){
            if(!map[bombY][bombX+i].wall){
                if(!map[bombY][bombX+i].object){
                    map[bombY][bombX+i].explosion = 1;
                }
                else
                    var explodeEast = false;
                    delete map[bombY][bombX+i].object;
                    map[bombY][bombX+i].explosion = 1;
            }
            else
                var explodeEast = false;
        }

        if(explodeSouth && map[bombY+i][bombX]){
            if(!map[bombY+i][bombX].wall){
                if(!map[bombY+i][bombX].object){
                    map[bombY+i][bombX].explosion = 1;
                }
                else
                    var explodeSouth = false;
                    delete map[bombY+i][bombX].object;
                    map[bombY+i][bombX].explosion = 1;
            }
            else
                var explodeSouth = false;
        }

        if(explodeWest && map[bombY][bombX-i]){
            if(!map[bombY][bombX-i].wall){
                if(!map[bombY][bombX-i].object){
                    map[bombY][bombX-i].explosion = 1;
                }
                else
                    var explodeWest = false;
                    delete map[bombY][bombX-i].object;
                    map[bombY][bombX-i].explosion = 1;

            }
            else
                var explodeWest = false;
        }

    }
    player.bombs++;
    }
}

```

If anyone can think of a good way to remove the explosion after a delay please help.

# Answer
Have you tried creating an Explosion object with its own lifetime? If you add the explosion tiles that you place to an array that's managed by some sort of supervisor, then you could add a `setTimeout(manager.deleteMe(X,Y), 100)` in an Explosion object.
> 3 votes

---
Tags: javascript, html5
---


title: Implementing invisible bones

text:
# Question
Title: Implementing invisible bones
I suddenly have the feeling that I have absolutely no idea how to implement invisible objects/bones.

Right now, I use hardware instancing to store the world matrix of every bone in a vertex buffer, and then send them all to the pipeline. But when dealing with frustum culling, or having them set to invisible by my simulation for other reasons, means that some of them will be randomly invisible.

Does this mean I effectively need to re-fill the buffer from scratch every frame with only the visible unit's matrices? This seems to me like it would involve a lot of wasted bandwidth.

# Answer
Might as well put this as an answer... I'd try implementing what I suggested and have units or objects that you want to be invisible reference a bone with zero scale. Really that's only for units that have multiple bones and you want to just make part of it invisible. Otherwise, just remove the position offset or change it to really far away when you want to make a unit invisible. Try letting the graphics card sort out what to draw.

You can't worry too much about performance yet. At least try these things out before disregarding them as to costly. Premature optimization and all that.
> 1 votes

---
Tags: directx9
---


# Question
Title: When is it best to load screens in mobile games?
In the develpment of a mobile game, is it a good to load all the screens at the start of the game, or destroy and create new ones during the game? I am doing the second thing, because I suppose that the first one consumes a lot of memory, what's recommended?

# Answer
> 3 votes
This totally depends on the nature of your game, and how much data is actually on each screen. My approach to this would be as follows: *avoid premature optimization*. With that said, let me elaborate a little, and explain how I've managed this in some of the games I've written for mobile devices.

I typically load textures as they are needed, because most (if not all) mobile devices have very limited memory. In order to keep performance high, I try to keep these textures around as long as possible, if there is a reasonable chance I'll need it again. A quick example:

I have a texture that is my pause screen. It has some button looking things, that have hotspots around these "buttons" and a few blank areas where I draw text. The first time the pause action is invoked, I pull up the texture and draw it, then when they resume I keep it around, in the event that they pause again. Now, if memory became an issue in this game, I'd ditch the pause menu texture when they resume, so far, its not been a problem.

# Answer
> 1 votes
Mobile devices are a lot more memory constrained than desktop platforms, so usually it is better to build screens on demand during the game. It's the usual efficiency tradeoff though, between processor usage and memory consumption.

# Answer
> 1 votes
Not sure what you mean by loading screens, but I'll try to answer for the general case of loading any asset / data.

The trade off basically comes down to efficiency and simplicity. Loading all assets up front is very simple because you never have to worry about whether something is loaded or not. You can handle dependencies (for example, a 3d model might depend on textures) explicitly in this case and avoid the complication altogether. However, you'll be loading things that may not be required at all, which incurs unnecessary load time and memory footprint.

If you load things as needed, you can potentially yield a better experience, because the user will only be forced to wait for as many assets to load as are actually required, and these loading times may be stretched out over several short periods. Additionally, you can keep your memory footprint to a bare minimum. However, you have some additional complications:

* What do you do when two independent things require the same resource? You need to both make sure that this resource isn't loaded twice and ensure that when one of these things no longer needs it that it isn't actually unloaded.
* You'll potentially need to have some checks to make sure that all loading is in before you continue. This might be additionally complicated by the fact that some things can only be done by one thread or another. If you only use one thread, you'll have to make sure that thread can service any code required to load assets during the loading period (for example, loading a texture into video memory can generally only be done by one specific thread.)

Some or all of this may not be relevant, depending largely on your context. So I would say that if you aren't in a situation that you need to be conservative about memory or long load times that you load everything up front and you won't ever need to worry about it. If, on the other hand, you feel the need to reduce or segment load screens / times or need to use the least amount of memory possible, design a system to allow you to load things at different times. Just be aware that the latter can come with some obnoxious complications.

---
Tags: android, performance, libgdx
---


# Question
Title: Velocity control of the player, why doesn't this work?
I have the following code inside a while True loop:

```
if abs(playerx) < MAXSPEED:
    if moveLeft:
        playerx -= 1
    if moveRight:
        playerx += 1

if abs(playery) < MAXSPEED:
    if moveDown:
        playery += 1
    if moveUp:
        playery -= 1

if moveLeft == False and abs(playerx) > 0:
    playerx += 1
if moveRight == False and abs(playerx) > 0:
    playerx -= 1
if moveUp == False and abs(playery) > 0:
    playery += 1
if moveDown == False and abs(playery) > 0:
    playery -= 1

player.x += playerx
player.y += playery

if player.left < 0 or player.right > 1000:
    player.x -= playerx
if player.top < 0 or player.bottom > 600:
    player.y -= playery

```

The intended result is that while an arrow key is pressed, `playerx` or `playery` increments by one at every iteration until it reaches `MAXSPEED` and stays at `MAXSPEED`. And that when the player stops pressing that arrow key, his speed decreases until it reaches 0.

To me, this code explicitly says that...

But what actually happens is that `playerx` or `playery` keeps incrementing regardless of `MAXSPEED` and continues moving even after the player stops pressing the arrow key.

I keep rereading but I'm completely baffled by this weird behavior. Any insights? Thanks.

# Answer
> ```
> if moveLeft == False and abs(playerx) > 0:
>     playerx += 1
> if moveRight == False and abs(playerx) > 0:
>     playerx -= 1
> if moveUp == False and abs(playery) > 0:
>     playery += 1
> if moveDown == False and abs(playery) > 0:
>     playery -= 1
>
> ```

I'm pretty sure this is where the problem lies. Taking the first one for example, you're saying that if the left key is not pressed and the player is moving in an x direction, increase the x.

Change the `abs(playerx) > 0` to `playerx < 0` and the following lines would be `playerx > 0`, `playery < 0`, and `playery > 0`, respectively.

Hope that does it!
> 3 votes

---
Tags: 2d, python
---


# Question
Title: How can I get started programming OpenGL on Mac OS X?
I'm trying to start OpenGL programming on a Mac, which brings me into unknown territory on a lot of things.

During the day, I'm a Web Developer, working in C# and before that in PHP and Delphi, all on Windows.

During the night, I try to pick up Mac/OpenGL skills, but everything is so different. I've been trying to look for some books, but the OpenGL books are usually for iOS (tons of them out there) and the Mac Books usually cover "normal" application Development.

I want to start simple with Pong, Tetris and Wolfenstein.

I see that there are a bunch of different OpenGL Versions out there. I know about OpenGL ES 1&2, but I don't know about the "big" OpenGL Versions - which ones are commonly supported on 10.6 and 10.7 on current (2010/2011) Macs? Are there any up to date (XCode 4) books or tutorials?

I don't want to use a premade Engine like Unity yet - again, I know next to nothing about any Mac development.

# Answer
> 7 votes
**OpenGL Versions**

OpenGL Versions supported depends on two factors on OS X:

* OS Version (10.7, 10.6, 10.5 ...)
* GPUs or drivers

But at least, you can use OpenGL 2.1 on every recent mac.

Note: OpenGL is the desktop version, and OpenGL ES is the mobile one. Don't use ES on desktop platforms.

Ps: if you have a GMA 950 Card (Intel chipset), you should have problems. Don't support them.

On my mbp, it is:

* OS X 10.7 (Lion), OpenGL 3.2 Core is supported.
* OS X 10.6 (Snow Leopard), OpenGL 3.0 Core is supported.

Use OpenGL Extensions Viewer to know OpenGL versions supported by your Hardware.

**Start OpenGL on OS X**

Use XCode 4.1 (4.2 beta for Completion with C++/C). They are samples provided by Apple for AGL, the link between OpenGL and Window system.

# Answer
> 2 votes
If you are experienced with C#, then better use Mono and OpenTK for your OpenGL learning. Mono is a free, cross-platform implementation of .NET (so you won't need to learn any new APIs) and OpenTK is a C# wrapper for all OpenGL functions, including some basic math, input and sound libraries.

# Answer
> 1 votes
Apple actually has a guide just for this very thing here.

---
Tags: opengl, macos
---


# Question
Title: OpenGL + Allegro. Moving from software drawing X Y to openGL is confusing
Having a fair bit of trouble. I'm used to Allegro and drawing sprites on a bitmap buffer at X Y coords. Now I've started a test project with OpenGL and its weird.

Basically, as far as I know, theirs many ways to draw stuff in OpenGL. At the moment, I think I'm creating a Quad? Whatever that is, and I think Ive given it a texture of a bitmap and them im drawing that:

```
GLuint gl_image;

bitmap = load_bitmap("cat.bmp", NULL);

gl_image = allegro_gl_make_texture_ex(AGL_TEXTURE_MASKED, bitmap, GL_RGBA);

glBindTexture(GL_TEXTURE_2D, gl_image);

glBegin(GL_QUADS);
    glColor4ub(255, 255, 255, 255);

    glTexCoord2f(0, 0); glVertex3f(-0.5, 0.5, 0);
    glTexCoord2f(1, 0); glVertex3f(0.5, 0.5, 0);
    glTexCoord2f(1, 1); glVertex3f(0.5, -0.5, 0);
    glTexCoord2f(0, 1); glVertex3f(-0.5, -0.5, 0);

glEnd();

```

So yeah. So I got a few questions:

Is this the best way of drawing a sprite? Is it suitable?

The big question: Can anyone help / Does anyone know any tutorials on this weird coordinate thing? If it even is that. It's vastly different from XY, but I want to learn it. I was thinking maybe I could learn how this weird positioning stuff works, and then write a function to try and translate it to X and Y coords.

Thats about it. I'm still trying to figure it all out on my own but any contributions you guys can make would be greatly appreciated =D

Thanks!

# Answer
> 5 votes
I'll try to address your specific questions.

> Is this the best way of drawing a sprite? Is it suitable?

It's suitable, and it works, but it's not the best way to do it.

**What gl\* calls really do**

What you are doing is sending commands to your video card. Just about any function you call that begins with 'gl' does so . Thraka did a fairly good job of explaining some of the commands you're using already.

The glTexCoord2f() and glVertex3f() function calls you are making interact with your video card drivers, which then send commands to the video card, which does all the real work.

The reason this isn't the best way to do it is because you are making a single function call *and* sending your data to the video card, for every vertex, every time you draw this quad. Imagine if you could send the data to the video card once, and then tell the video card to draw "that thing" you sent earlier, instead of telling it each time you draw what the coordinates are. This is referred to as a Vertex Buffer Object, or VBO.

> Can anyone help / Does anyone know any tutorials on this weird coordinate thing?

Now it looks like you're just getting started, so I wouldn't worry too much about anything I just said. I especially wouldn't worry about using the most efficient way of rendering things. Hopefully it gives you an idea of what you're really doing, though, when you make these function calls.

To really understand the relationship between the X and Y coordinates you worked with in Allegro and the 3 dimensional coordinates (and the immense flexibility therein that OpenGL gives you), you really need a good math background.

I believe it was pre-calculus where I learned about rotations, scale, and translation, and how a 3x3 matrix could be used to represent all these things in a two-dimensional space. If I had paid more attention then, I might be a better game developer today, but that's beside the point. This is the kind of thing that's fundamental to understanding how to work with OpenGL. Of course, OpenGL is a 3-dimensional API, so things therefor get a little more complicated, but the same way of thinking extends well. However, you can get by without understanding the intricate details of transformation matrices as long as you understand some basic concepts.

**Coordinate spaces**

Think back to some geometry (or similar) studies you've done. You usually describe the position, shape, size, and so on of an object relative to the origin ( (0, 0) in a two dimensional space). If you say a point is at (2, 2) you are saying it is *up two* and *right two* from the origin.

What is this origin? A better question is *where is it*? It's completely arbitrary. You can't tell someone your house is at (x, y) and expect them to know how to get there. You could possibly give them the latitude and longitude of your house, but these are coordinates in a similarly arbitrary coordinate system. Latitude and Longitude only have any meaning because everyone agrees where the Prime Meridian and the Equator are.

Similarly, there are directions involved. In a 3D world, there is an up, a right, and a forward. This is incredibly intuitive to you because your right hand has always been your right hand, up has always been up, and forward has always been in front of you. But in an arbitrary coordinate space like we are talking about, these things have to be specified before anything makes any sense.

When you work with OpenGL, you need to think in similar terms. If you tell OpenGL to draw something at (0, 0) you're telling it to draw at the origin of the *current coordinate space.* This coordinate space defines where the origin is, these principal directions, and some other things like scale that may be important.

I'll try to give an example of how this could all be practically used.

Imagine you have taken your room and modeled it all in something like Google Sketchup (or any other 3D modelling program.) You've got windows, your bed, and your computer in there. Where is the origin? What is right, up, and forward? Lets say you just started modeling everything without thinking about any of this, and these things happen to correspond to the doorway to your room. That is, in your virtual world, you are at the origin and looking forward when you are standing in the doorway facing your room.

Now you've saved this whole virtual world (your room) to a file. And you've decided to model the rest of your house. You start a new virtual world (your house) and put the other rooms in there, the backyard, kitchen, etc. Now lets say you've modeled everything in your house except your room. First, lets consider where the origin of this virtual world is. We'll say you decided to call it, again, the doorway to your house. The origin is the doorway to your house, forward is the direction you are facing when you look into the house, etc.

All the items in your room are saved currently relative to the doorway to your room. But you want to pull your room that you previously modeled into your house. What needs to happen (and what the modelling program will do for you automatically) is that you define the position and rotation of your room *relative to the coordinate space of your house.*

Assume, now, that we have "your room" positioned in your house relative to the front door. How do you determine where, in your house, the computer is in your room? You have to transform the computer's coordinates from your rooms' coordinate system to the coordinate system of the house. Since you've defined the orientation of your room relative to your house, you can now do this.

**How this relates**

Imagine the computer monitor you are currently looking at is a camera, or an eye, looking into a virtual world. If you play a first-person-shooter for a bit, this isn't hard to do. The monitor, of course, isn't actually moving; it's only depicting a changing perspective into a virtual world.

From this point of view, how might you make the impression of a two dimensional space, like many games (such as Mario)? Imagine (again) that you take a board game, like Monopoly, and want to film it. The board game is essentially 2-dimensional, but the camera you are using captures an entire 3-dimensional world. If you place the board of Monopoly on a flat table, and then position your camera a couple feet above the board, facing directly downward towards it, you'd end up capturing the Monopoly world in its 2-dimensional glory.

This is **exactly(1)** what Allegro does for you. You give it two dimensional coordinates and it translates them into 3-dimensional coordinates that work out exactly the way you want.

**Matrices**

One convenient way of doing all of this is by using a matrix. As I said earlier, orientations in a 2-dimensional space can be described by a 3x3 matrix. Similarly, orientations in a 3-dimensional space can be described by a 4x4 matrix. The real convenient thing here is that to "jump" from one coordinate system to another, you just have to multiply the existing matrix by another.

If you describe the location of the computer in your room as a 3-dimensional vector, you can multiply this vector by the room's transformation matrix to find its position in the house-space. The matrix math would look something like this:

```
[ n, n, n, n,     [ x,
  n, n, n, n,   *   y,
  n, n, n, n,       z ]
  n, n, n, n ]

```

I don't want to bog you down with the specific numbers in the matrix and their meaning, but this should give you an idea of the relationship. The 4x4 matrix on the left is our theoretical transformation matrix that describes your room's orientation, and the vector on the right (or 1x3 matrix, if you will) describes the position of your computer relative to your room.

Back to our house example, lets imagine a third coordinate space. Lets say this is the city, and that the origin is at the city hall, and that this coordinate space is facing north. Now we have 3 coordinate spaces, described by 3 matrices:

M1 - city

M2 - house

M3 - room

And we have one particular object, your computer, with a vector describing it's location relative to the room:

V1

We can do some pretty cool stuff now:

The position of your computer relative to the house is:

```
M3 * V1

```

The position of your computer relative to the city is:

```
M2 * M3 * V1

```

And if we say the city's coordinate space is relative to "world space," we can say that the position of your computer relative to "world space" is:

```
M1 * M2 * M3 * V1

```

**Good luck**

I'm tired of writing, and unfortunately there's still a bit more in your question that may not have been answered (specifically about texture coordinates.) Hopefully my voluminous answer has helped you understand the code you're writing though, and helped you understand some of the concepts needed to work with OpenGL.

--

(1) Allegro may not do exactly this, but this should give you the idea of the relationship between 2D and 3D in OpenGL.

# Answer
> 3 votes
I've never used OpenGL and I'm not that good at the other things I've used in the 3D world. But basically the way programming works in 3D is that you give render instructions to the graphics card. If I interpret your code it's saying

**glBindTexture(GL\_TEXTURE\_2D, gl\_image);**

-- I'm going to use this texture

**glBegin(GL\_QUADS);**

I'm going to draw quads to the screen. A quad is made up of 4 points and represents a flat surface, so it's going to process four points to draw a quad. So if you decalred 8 verticies(sp?) then it would make two quads.

**glTexCoord2f(0, 0); glVertex3f(-0.5, 0.5, 0);**

Use this texture coordinate and use this 3d world space coordinate.

A texture coordinate maps a to a location on your texture. If you think of your texture as a rectangle and the top left is the coordinate 0.0 , 0.0 and the bottom right coordinate is 1.0 , 1.0 then any number between 0.0 and 1.0 along any axis will plot a space in the texture. Where 0 and 1 are depends on how OpenGL will interpret this data. it may be that 0,0 is the bottom left and 1,1 is the top right.

Think if the center of your screen (by default) as world space 0.0 , 0.0. When you say -0.5 , 0.5 then it is probably moving a little to the left and a little up to plot that first point (vertex) depending on how OpenGL declares it's coordinate system.

Since you do this four times, you are declaring where each point is going to draw in the world and what part of the texture it will use.

I found this image online:

I think this shows you how a texture coordinate is used by a quad. t0 is the first texture coordnate you declared on the texture (0,0 i'm assuming in the picture) and that point of the texture will be rendered

If you go into quad rendering then when you define four verticies, think of it as connecting a line between all four points and then rendering the texture in it based on where you said each vertex would be on the texture.

---
Tags: opengl, allegro
---


# Question
Title: Can minecraft support an asymmetrical mesh?
I want to play as a Zaku II from gundam in Minecraft. I was saddened that player skins must be symmetrical. I know there's a mod that lets you play as a MLP pony, and another one that let you shapeshift into mobs.

So I decided I could just modify the player model mesh and with a shoulder spike and shield. Apply a Zaku skin to it, port the colors over onto more texture for the shoulder portions, and add it to the shiftable list. Then modify a gun mod to turn a gun into a ZMP-78.

Before I get started on this though, I need to know if Minecraft will support an asymmetrical mesh.

# Answer
Why don't you just try it? It would take like... 5 minutes?

Anyways, if I'm not mistaken, Minecraft doesn't work with meshes. It's just a bunch of rectangular parallelepipeds stuck into each other (or at least it WAS like that some time ago.)
> 5 votes

---
Tags: models, minecraft-modding
---


# Question
Title: Proper way to do texture mapping in modern OpenGL?
I'm trying to do texture mapping using OpenGL 3.3 and GLSL 150.

The problem is the texture shows but has this weird flicker I can show a video here.

My texcords are in a vertex array. I have my fragment color set to the texture values and texel values. I have my vertex shader sending the texture cords to texture cordinates to be used in the fragment shader. I have my ins and outs setup and I still don't know what I'm missing that could be causing that flicker.

Here is my code:

**Fragment shader**

```
#version 150

uniform sampler2D texture;
in vec2 texture_coord;

varying vec3 texture_coordinate;
void main(void) {
    gl_FragColor = texture(texture, texture_coord);
}

```

**Vertex shader**

```
#version 150

in vec4 position;
out vec2 texture_coordinate;
out vec2 texture_coord;
uniform vec3 translations;

void main() {
    texture_coord = (texture_coordinate);
    gl_Position = vec4(position.xyz + translations.xyz, 1.0);
}

```

**Last bit**

Here is my vertex array with texture coordinates:

```
GLfloat vVerts[] = {
   0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
   0.0f, 0.5f, 0.0f, 1.0f, 1.0f,
   0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
   0.5f, 0.0f, 0.0f, 1.0f, 0.0f}; //tex x and y

```

If you need to see all the code, here is a link to every file.

Thank you for your help.

# Answer
1. In your vertex shader, `texture_coordinate` is declared as an `out` variable, but you use it as if it were an input. You might be collecting trash data here. You meant it to be an `attribute` (deprecated in GLSL 1.50, that's just `in` for your vertex shader.) It's surprising you didn't get at least a warning (which you probably have but didn't notice, are you checking the error log?)
2. `texture_coordinate` and `texture_coord` are both `vec2`, but then in your fragment shader, `texture_coordinate` is a `vec3`, so types do not match.
3. `varying` is deprecated in GLSL 1.50 so I encourage you not to use it. It's inferred from the `in`/`out` qualifiers in each shader and the different interpolation qualifiers (`smooth`, `flat` and `noperspective`.)

There are several problems in your shader which seem to be the consequence of heavy copy-pasting from tutorials involving different GLSL versions. You might want to check GLSL 1.50 reference thoroughly and the error log to avoid these.
> 5 votes

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


# Question
Title: How do I detect the direction of 2D rectangular object collisions?
After this question, I need some more help.

How can I find out which side of a rectangle a collision came from and react accordingly?

The blue arrows are the paths that some circular objects would follow if before and after colliding with the box.

How can I calculate this?

# Answer
Since this is based on your other question I'll give a solution for when the rectangle is axis-aligned.

First, you build up you current object's rectangle with the following values:

```
int boxLeft = box.X;
int boxRight = boxLeft + box.Width;
int boxTop = box.Y;
int boxBottom = boxTop + box.Height;

```

Next, you must have the old object's position (which you can store on each object or simply pass to a function) to create the old object's rectangle (when it was not colliding):

```
int oldBoxLeft = box.OldX;
int oldBoxRight = oldBoxLeft + box.Width;
int oldBoxTop = box.OldY;
int oldBoxBottom = oldBoxTop + box.Height;

```

Now, to know where the collision was from, you must find the side where the old position was not in the collision area and where its new position is. Because, when you think of it, this is what happens when you collide: a side that was not colliding enters an other rectangle.

Here is how you could do so (these functions assume that there is a collision. They should not be called if there is no collision):

```
 bool collidedFromLeft(Object otherObj)
{
    return oldBoxRight < otherObj.Left && // was not colliding
           boxRight >= otherObj.Left;
}

```

Rince and repeat.

```
bool collidedFromRight(Object otherObj)
{
    return oldBoxLeft >= otherObj.Right && // was not colliding
           boxLeft < otherObj.Right;
}

bool collidedFromTop(Object otherObj)
{
    return oldBoxBottom < otherObj.Top && // was not colliding
           boxBottom >= otherObj.Top;
}

bool collidedFromBottom(Object otherObj)
{
    return oldBoxTop >= otherObj.Bottom && // was not colliding
           boxTop < otherObj.Bottom;
}

```

Now, for the actual use with the collision response from the other question:

```
if (collidedFromTop(otherObj) || collidedFromBottom(otherObj))
    obj.Velocity.Y = -obj.Velocity.Y;
if (collidedFromLeft(otherObj) || collidedFromRight(otherObj))
    obj.Velocity.X = -obj.Velocity.X;

```

Again, this may not be the best solution but that's the way I usually go for collision detection.
> 8 votes

# Answer
As the question is partially identical to this question, I will re-use some parts of my answer in order to try answering your question.

---

Lets define a context and some variables to make the following explanation more understandable. The representation form that we will use here probably doesn't fit the form of your own datas but it should be simpler to understand this way (indeed you can use the following methods using others kind of representations once you understand the principle)

So, we will consider an **Axis Aligned Bounding Box** (or an **Oriented Bounded Box**) and a **moving Entity**.

* The Bounding Box is composed of 4 sides, and we will define each one as:
Side1 = **\[x1,y1,x2,y2\]** (two points \[x1,y1\] and \[x2,y2\])
* The moving Entity is defined as a velocity vector (position+speed):
a position **\[posX, posY\]** and a speed **\[speedX, speedY\]**.

---

You can determine which side of an AABB/OBB is hit by a vector using the following method:

* 1/ Find the intersection points between the infinite lines passing though the four sides of the AABB and the infinite line passing through the entity position (pre-collision) which use the entity speed vector as slop. (You can either find a collision point or an undefined number, which corresponds to parallels or overlapping lines)
* 2/ Once you know the intersection points (if they exist) you can search for those that are into the segment bounds.
* 3/ Finally, if there is still multiple points on the list (the velocity vector can pass through multiple sides), you can search for the closest point from the entity origin using the magnitudes of the vector from the intersection to the entity origin.

Then you can determine the angle of collision using a simple dot product.

* 4/ Find the angle between of collision using a dot product of the entity (probably a ball?) vector with the hit side vector.

## ----------

More details:

* 1/ Find intersections

+ a / Determine the infinite lines ( Ax + Bx = D ) using their parametric forms ( P(t) = Po + tD ).

    > Point origin: Po = \[posX, posY\]
    > Direction vector: D = \[speedX, speedY\]
    > **A** = D.y = **speedY**
    > **B** = -D.x = **-speedX**
    > **D** = (Po.x * D.y) - (Po.y * D.x) = **(posX*speedY) - (posY*speedX)**
    > Ax + By = D \<====\> (speedY*x) + (-speedX*y) = (posX*speedY) - (posY*speedX)

    **I used the entity point values to illustrate the method, but this is exactly the same method to determine the 4 side infinite lines of the bounding box** (Use Po = \[x1,y1\] and D = \[ x2-x1 ; y2-y1 \] instead).
    + b / Next, to find the intersection of two infinite lines we can solve the following system:

    > A1x + B1x = D1 \<== Line passing through the entity point with the speed vector as slop.
    > A2x + B2x = D2 \<== One of the lines passing through the AABB sides.

    which yields the following coordinates for the interception:

    > Interception **x** = ((**B**2\***D**1) - (**B**1\***D**2)) / ((**A**1\***B**2) - (**A**2\***B**1))
    > Interception **y** = ((**A**1\***D**2) - (**A**2\***D**1)) / ((**A**1\***B**2) - (**A**2\***B**1))

    If the denominator ((A1\*B2) - (A2\*B1)) equals zero, then the both lines are parallels or overlapping, otherwise you should find an intersection.
* 2/ Test for the segment bounds. As this is straightforward to verify, there is no needs for more details.
* 3/ Search for the closest point. If there is still multiple points on the list, we can find which side is the closest to the entity origin point.

+ a / Determine the vector going from the intersection point to the entity origin point

    > V = Po - Int = \[Po.x - Int.x ; Po.y - Int.y \]
    + b / Compute the vector magnitude

    > ||V|| = sqrt( V.x² + V.y² )
    + c / find the smallest one.
* 4/ Now that you know which side will be hit, you can determine the angle using a dot product.

+ a / Let **S = \[ x2-x1 ; y2-y1 \]** be the side vector that will be hit and **E = \[ speedX ; speedY \]** be the entity velocity vector.
    Using the vector dot product rule we know that

    > S·E = Sx*Ex + Sy*Ey
    > and
    > S·E = ||S|| ||E|| cos θ

    So we can determine θ by manipulating a bit this equation...

    > cos θ = (S·E) / (||S|| ||E||)
    > **θ = acos( (S·E) / (||S|| ||E||) )**

    with

    > **S·E** = Sx * Ex + Sy * Ey
    > **||S||** = sqrt( Sx² + Sy² )
    > **||E||** = sqrt( Ex² + Ey² )

---

Note: As I said in the other question thread, this is probably not the most efficient nor the most simple way to do it, this is just what's come into mind, and some part of the maths could maybe help.

I didn't verified with a concrete OBB example (I did with an AABB) but it should works too.
> 7 votes

# Answer
A simple way is to resolve the collision, then translate the moving object's collision box by one pixel in each direction in turn and see which ones result in collision.

If you want to do it "properly" and with rotated collision shapes or arbitrary polygons, I suggest reading up on the Separating Axis Theorem. Metanet software (the folks who made the N game) for instance have an awesome dev article on SAT. They also discuss the physics involved.
> 6 votes

# Answer
One way would be to rotate the world around your rectangle. "The world" in this case is only the objects you care about: the rectangle, and the ball. You rotate the rectangle around its center until its bounds are aligned with the x-/y-axes, then you rotate the ball by the same amount.

**The important point here is that you rotate the ball around the rectangle's center, not its own.**

Then you can easily test for collision just like you would with any other non-rotated rectangle.

---

Another option is to treat the rectangle as four distinct line-segments, and test for collision with each of them separately. This allows you to test for collision *and* figure out which side was collided at the same time.
> 2 votes

# Answer
I used fixed angles in my calculations, but this should help you some

```
void Bullet::Ricochet(C_Rect *r)
{
    C_Line Line;
    //the next two lines are because I detected
    // a collision in my main loop so I need to take a step back.

    x = x + ceil(speed * ((double)fcos(itofix(angle)) / 65536));
    y = y + ceil(speed * ((double)fsin(itofix(angle)) / 65536));
    C_Point Prev(x,y);

    //the following checks our position to all the lines will give us
    // an answer which line we will hit due to no lines
    // with angles > 90 lines of a rect always shield the other lines.

    Line = r->Get_Closest_Line(Prev);
    int langle = 0;
    if(!Line.Is_Horizontal())   //we need to rotate the line to a horizontal position
    {
        langle = Line.Get_Point1().Find_Fixed_Angle(Line.Get_Point2());
        angle = angle - langle;  //to give us the new angle of approach
    }
    //at this point the line is horizontal and the bullet is ready to be fixed.
    angle = 256 - angle;
    angle += langle;
}

```
> 1 votes

---
Tags: 2d, collision-detection, physics
---


# Question
Title: Knowledge of a Language vs. Games in Portfolio
How important is the knowledge of a language versus the games that you have developed in your portfolio?

To be more specific. Personally, I dislike C++ for several reason(mainly due to it's complexity, and pointers, and I prefer D as my language of choice thus far. Due to this, I've written two games in D instead of C++ that are my personal projects. Am I wasting my time with D? Should I start using C++ again?

For reference, I have 6 months of experience in C++. It's the first language I learned. I have messed around with SDL/SFML and a bit of Direct3D with C++ as well.

Even though I like D, i'd rather not waste my time learning it, if it in no way will help me get a job in the gaming industry.

# Answer
It depends on what sort of games you want to make. If you are talking consoles or big studio PC games, the vast majority is C++ with maybe a few plain old C holdouts still around. That doesn't mean it will always be that way, D very well could become the standard in a few years if enough people get into it and quality tools are developed but so far I've never heard of a commercial game using it... or any game for that matter yet.

This doesn't mean that it's a waste of time though! Knowing multiple languages is important, even if you don't end up using all of them on a regular basis. Much like with spoken language, learning a new programming language can actually improve your skills with other languages as you come to understand general concepts about programming. Also, by understanding how the same concept can be implemented in a different syntax and/or paradigm, it will make it easier to learn additional new languages, which may be a requirement. Adaptability is an important skill. For instance, my current project at work is using Scala, a language I had never touched prior to the start of the project.

Having knowledge of the language(s) that a company uses is definitely desirable, but **far more important** is your fundamental understanding of things like data structures, algorithms and architecture. You can get a programming job based on those merits even if you aren't familiar with the particular language a company uses, but *not* vice versa.
> 4 votes

# Answer
I gave Jason's answer a +1 for content, but I disagree with the overall verdict. In the traditional gaming industry you're going to be staring at C++ 8 hours a day (or more) so you need to be very comfortable with it, even if it's not your 1st choice. If your portfolio shows that you basically avoided C++, then a prospective employer is likely to have second thoughts about whether you can adapt to their existing code base. Understanding the important concepts about data structures and algorithms is also essential, but if there's any doubt that you're able to implement them in C++, then you would be at a serious disadvantage compared to someone who's got evidence of that ability. For example, you may dislike pointers but being good with them has been essential in all game engines I've worked with.

If I were in your position I'd firstly decide what I meant by "the gaming industry" because that is changing a lot and there are lots of games now, eg. on mobile, web, tablets, etc, which don't use C++. But if you wanted to aim for the traditional AAA market I would say a portfolio needs to primarily be of C++ programs, with a D program thrown in as evidence that you are not limited to one language.
> 7 votes

# Answer
C++ is a great language. It isn't very complex: the learning curve is fine, level of entry is low, and pointers are awesome! No better way to learn about variables, memory, functions and so on... I used to recommend Python as someone's first language, but I avoid doing so now. Why? Because Python is a really abstract language. You wont learn a lot about how computers work on a lower level if you start with Python.

So, I seriously recommend that you start learning C++. It has a much larger userbase and codebase than D, and it's the industry standard for the AAA. However, if you only plan is to make smaller indie games, then it might suit you fine. The problem is that as soon as you expand your team to have more programmers, you'll run into troubles. Chances are, they wont know D... But, as you stated, you're interested in getting a job, so yeah, you should use C++.

Also, you are not "wasting your time with D". Programming isn't wasting time. Once you grasp the basics of a language, that algorithm you learned with D can sure as hell be coded in C++ or Python. So, after some time, you're not learning a language, you're learning to program. This has a lot to do with your portofilio, if you made collision detection in one language, it isn't hard to make it in another.
> 0 votes

---
Tags: c++
---


# Question
Title: How to perform simple collision detection?
Imagine two squares sitting side by side, both level with the ground like so:

A simple way to detect if one is hitting the other is to compare the location of each side. They are touching if all of the following are false:

* The right square's left side is to the right of the left square's right side.
* The right square's right side is to the left of the left square's left side.
* The right square's bottom side is above the left square's top side.
* The right square's top side is below the left square's bottom side.

If any of those are true, the squares are not touching. But consider a case like this, where one square is at a 45 degree angle:

Is there an equally simple way to determine if those squares are touching?

# Answer
> 7 votes
What you're looking for is called the Separating Axis Theorem. A tutorial of it can be found here.

Essentially what you want to do, in the case of Object Oriented Bounding Boxes (rotated squares) is project the half-vectors of those squares, let's say 'up' and 'right,' onto the axes in the coordinate spaces of each square. You also project the vector between the square centers on these axes. If, for any axis, the sum of the lengths of the projected half vectors is greater than the length of projected distance between the two squares, then they are not colliding.

---
Tags: collision-detection, geometry
---


title: Bomberman clone, how to do bombs?

text:
# Question
Title: Bomberman clone, how to do bombs?
I'm playing around with a bomberman clone to learn game-developement.

So far I've done tiles, movement, collision detection, and item pickup. I also have pseudo bombplacing (just graphics and collision, no real functionality).

I've made a jsFiddle of the game with the functionality I currently have. The code in the fiddle is very ugly though. Scroll past the map and you find how I place bombs.

Anyway, what I would like to do is an object, that has the general information about bombs like:

```
function Bomb(){
  this.radius = player.bombRadius;
  this.placeBomb = function (){
    if(player.bombs != 0){
      // place bomb
    }
  }
  this.explosion = function (){
  // Explosion
  }
}

```

I don't really know how to fit it into the code though. Everytime I place a bomb, do I do `var bomb = new Bomb();` or do i need to constantly have that in the script to be able to access it.

How does the bomb do damage? Is it as simple as doing X,Y in all directions until radius runs out or object stops it? Can I use something like setTimeout(bomb.explosion, 3000) as timer?

Any help is appreciated, be it a simple explanation of the theory or code examples based on the fiddle. When I tried the object way it breaks the code.

**Update:** I now place bombs, and after a certain amount of time delete it depending on the position I placed it. But if I place a bomb before the first bomb explodes it only deletes one of them (obviously since bombX and bombY has changed since the first was placed).

Now i need to know how to fix this issue, maybe create a new array with all of the bomb positions? What's the best way of doing this?

Current code:

```
function placeBomb(){
    if(placebomb && player.bombs != 0){
        map[player.Y][player.X].object = 2;
        bombX = player.X; bombY = player.Y;
        placebomb = false;
        player.bombs--;
        setTimeout(explode, 3000);
    }
}
function explode(){
    alert('BOOM!');
    delete map[bombY][bombX].object;
    player.bombs++;
}

```

# Answer
It doesn't look that bad, but you need better control of timing and input. As it is movement speed is dependent on the keystroke repetition setting on the users machine, that is not exactly optimal.

Instead you should track which keys are currently being held down, you can do this like (in pseudocode):

```
keyisdown=false
keydown event{
    if(!keyisdown){
        //This is the 'real' keydown event, the one that only happens the moment the
        //key is pressed down. You may not need it, but this is how you construct it.
    }
    keyisdown=true
}

keyup event{
    keyisdown=false
}

```

And then in your update function you move the player if `keyisdown`, and possibly you apply some other conditions, like the player can't move if he moved less than some number of updates ago.

Keep an updated counter or some other way of keeping track of time so that your code always know exactly how far progressed it should be.

**Da bomb**
Personally I'd keep it simple, you don't actually need to use `this`, `new` and all the other fancy stuff in JavaScript to make useful objects.

You could do something like:

```
bombobject = {} //That is all it takes to make an object.
bombobject.blowtime = currenttime + delay
bombobject.position = mapobject
mapobject.bomb = bombobject

```

Then you can cycle through the map on every update, check if there is a bomb and if it's time to blow, if so blow and remove the bomb object.

**Bugtracking**
Your code is leaking errors, they are pretty simple, but if you don't learn about them and handle them you are going to have problems later on. Every modern browser has a Firebug clone developer console. Open it, look at the script console tab, see all the nasty red text and fix it.

**Edit: Timekeeping concerns**
Just for the record, you'd probably want something slightly more advanced than `setInterval` for timing, if you are serious you really need to make your code adjust for the timeslip. See my very first Stack Overflow answer for an approximate description of the problem: https://stackoverflow.com/a/2549426/305545

**Edit: setTimeOut version fixed**
Since you are using the same variables for different bombs you are going to overwrite them whenever a new bomb is placed. You can use a closure to make individual variables for each bomb, like so:

```
function placeBomb(){
    if(placebomb && player.bombs != 0){
        map[player.Y][player.X].object = 2;
        var bombX = player.X;
        var bombY = player.Y;
        placebomb = false;
        player.bombs--;
        setTimeout(explode, 3000);
    }
    function explode(){
        alert('BOOM!');
        delete map[bombY][bombX].object;
        player.bombs++;
    }
}

```

Now the `bombX` and `bombY` variables and the `explode` function are locals to the closure created by placeBombs, thus it is the local instance of `explode` that is attached to the timeout, and it reads the local variables. Each time you call `placeBomb` a new closure is created.

I wouldn't have used setTimeout for this, I would have counted updates, thus ensuring a fixed number of updates before the bomb blows, but I guess this will work ok.
> 6 votes

# Answer
Seems like you got a pretty nice awnser, just wanted to add some handy code for the explosions.

```
            for (int i = 0; i < actor.blasradius; ++i)
        {
            tiles[actor.tileX - i][actor.tileY].explode(); //left
            tiles[actor.tileX + i][actor.tileY].explode(); //right
            tiles[actor.tileX][actor.tileY -i].explode(); //up
            tiles[actor.tileX][actor.tileY + i].explode(); //down
        }

```
> 0 votes

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


title: Screen space to world space

text:
# Question
Title: Screen space to world space
I am writing a 2D game where my game world has *x* axis running left to right, *y* axis running top to bottom, and *z* axis out of the screen:

Whilst my game world is top-down, the game is rendered on a slight tilt:

I'm working on projecting from world space to screen space, and vice-versa. I have the former working as follows:

```
var viewport = new Viewport(0, 0, this.ScreenWidth, this.ScreenHeight);
var screenPoint = viewport.Project(worldPoint.NegateY(), this.ProjectionMatrix, this.ViewMatrix, this.WorldMatrix);

```

The `NegateY()` extension method does exactly what it sounds like, since XNA's *y* axis runs bottom to top instead of top to bottom. The screenshot above shows this all working. Basically, I have a bunch of points in 3D space that I then render in screen space. I can modify camera properties in real time and see it animate to the new position. Obviously my actual game will use sprites rather than points and the camera position will be fixed, but I'm just trying to get all the math in place before getting to that.

Now, I am trying to convert back the other way. That is, given an *x* and *y* point in screen space above, determine the corresponding point in world space. So if I point the cursor at, say, the bottom-left of the green trapezoid, I want to get a world space reading of (0, 480). The *z* coordinate is irrelevant. Or, rather, the *z* coordinate will always be zero when mapping back to world space. Essentially, I want to implement this method signature:

```
public Vector2 ScreenPointToWorld(Vector2 point)

```

I've tried several things to get this working but am just having no luck. My latest thinking is that I need to call `Viewport.Unproject` twice with differing near/far *z* values, calculate the resultant `Ray`, normalize it, then calculate the intersection of the `Ray` with a `Plane` that basically represents ground-level of my world. However, I got stuck on the last step and wasn't sure whether I was over-complicating things.

Can anyone point me in the right direction on how to achieve this?

# Answer
I think your idea is pretty much spot on! First calculate a ray for your cursor using both the near plane and the far plane as Z values for your 2D coordinates (i.e. use 0 and 1 for your Z coordinate). Here's an helper method to handle that:

```
public Ray GetScreenRay(Vector2 screenPosition, Viewport viewport, Matrix projectionMatrix, Matrix viewMatrix, Matrix worldMatrix)
{
    Vector3 nearPoint = viewport.Unproject(new Vector3(screenPosition, 0f), projectionMatrix, viewMatrix, worldMatrix);
    Vector3 farPoint = viewport.Unproject(new Vector3(screenPosition, 1f), projectionMatrix, viewMatrix, worldMatrix);
    return new Ray(nearPoint, Vector3.Normalize(farPoint - nearPoint));
}

```

Next you'll need to have a `Plane` instance that matches your ground. The easiest way to calculate it is to use the constructor that takes three points on the plane, and passing it any three vertices from the ground object. Example of how to calculate the ground plane:

```
Plane groundPlane = new Plane(ground.Vertices[0], ground.Vertices[1], ground.Vertices[2]);

```

And finally find the intersection point between the ray and the plane using this method. You can use the out result parameter in order to calculate the intersection coordinates like in the example below:

```
float? result;
mouseRay.Intersects(ref groundPlane, out result);
if(result != null)
    Vector3 worldPoint = mouseRay.Position + mouseRay.Direction * result.Value;

```

You might have to do something about the `NegateY` method too but I'm not sure where.
> 5 votes

---
Tags: xna, c#, matrix, projection, screen
---


# Question
Title: What C++ libraries can be used in game development
I'm currently in the planning stage for my next game, and since I've been away from C++ for a while I have some questions about helpful libraries. I plan on making a 2D game with SDL, constructing my own simple 2D engine. I plan on making this game for the PC.

What libraries would you recommend to make this process easier?

What about unittests?

What about an enforce operator to throw exceptions?

```
int a = 1;
enforce(a == 2); //Throws an exception,

```

Specifically, i'm looking for general purpose libraries, that implement that make my life easier (like boost). Also, a helpful library for physics/collision, AI, XML file parsing (specifically working with the Tiled map editor), and any others that you guys have used that are useful in a 2D game.

# Answer
Come up with a game first, see what you want and need. When you have specific problems, you can use google to solve most of them, for the remaining few there's gamedev.stackexchange.

I can suggest Box2D, because it's a great physics library, but what's that doing for you, you'll go "there's a 2D physics library, maybe i'll make a 2D game with physics in it"? That's the absolute wrong way of going about designing games.

I can suggest SFML for 2D graphics, but that's not right aswell. What if you want a game with complex visual effects or you want the ability to texture random polygons, you can't do that with SFML.

Pick your tools for the job, not the other way around.
> 4 votes

# Answer
boost::foreach works pretty much the way you want :)

Wikipedia has a nice list of C++ unit testing frameworks.

You could make your own enforce function pretty easily, something like this I suppose:

```
void enforce (bool expression)
{
    if (!expression) throw Exception(5);
}

```

where Exception would be a class defined by you. How you go from this to an enforce function that tells you more about what went wrong though, I'm not sure.
> 1 votes

# Answer
AI will be game specific. There are not a lot of general AI libraries, and even fewer designed for 2D problems.

Regarding other libraries, since you mentioned Boost, just use that.

For your "enforce" function, you need only a simple assert system. It takes only a few minutes to build your own. I would recommend against having it throw exceptions. Exceptions have a lot of problems, I'm fairly certain you're not at the level of writing exception safe code, and when it comes to debugging the exception model loses a lot of useful information. I have my assert macros log the failed test, the file/line/function, call \__debugbreak(), and then abort. Much better for debugging than an exception ever will be. Of course only intended for programming errors and not errors of invalid user input, but the latter if better dealt with in other ways anyway.

Box2D is the popular choice for physics in 2D games.

Finally, for unit tests, you might check out Googles test library. Though again, writing your own simple version of that takes a matter of minutes if you have a decent proficiency in C++.
> 1 votes

# Answer
Simple OpenGL Image Library, devIL, and AssImp are some fairly nice content importers.

Configurable Math Library is a fairly nice linear algebra library, and I believe boost has one as well.

And finally, FreeType-GL is a text-drawing library that I haven't used, but should work fairly well
> 1 votes

# Answer
I have to second what @dreta said about coming up with the game first, and figuring out what you may need... That being said, since you're using SDL for 2D, obviously SDL has lots of libs that were made just for it to help you out. SDL\_mixer, SDL\_ttf, SDL\_image are all obvious choices for basic tasks. Box2D, Torque 2D, ODE are all great choices for physics, ODE though it's recommended to be outdated and is technically no longer under construction officially, was used by the game World Of Goo. Which has incredible physics and I've not seen a single physics glitch in the three times I've beaten it (personally).

Regardless of whether your game is 2D/3D whatever, I've always been a sucker for a useful script engine. So Lua and Python would be my first choices any day. People say that Python is not good for an embedded or extension script engine for games, but I've used it personally and it's equivalent Lua codes worked actually slower than the Python. I've heard of people using JavaScript in games also, a big one to note is Wolfire's Overgrowth which uses JavaScript for interaction with the other world stuff.

As far as graphics go, it's well known, easy to set up, and perfectly acceptable to use OpenGL built into your SDL games, even for 2D graphics. One game to name that isn't released yet that we're expecting new videos on soon is the http://elysianshadows.com/ project which uses OpenGL accelerated SDL, for 2D.

For XML I stick with tinyXML almost all of the time, it's a great library and it works extremely fast with relatively minimal overhead. To me it just feels cleaner than other XML libraries.

PS: I didn't really get into the other stuff you mentioned, because it looks like everyone else provided great answers for those.
> 0 votes

---
Tags: c++
---


# Question
Title: Passing an objects rotation down through its children
In my topdown 2d game you have a player with a sword, like an old Zelda game.

The sword is a seperate entity, and its collision box "rotates" around the player like an orbit, but always follows the player wherever he goes.

The player and sword both have a vector2 heading. The sword is a weapon object that is attached to the character.

In order to allow swinging in a direction, I have the following property inside sword (RotateCopy returns a copy of the mHeading after rotation)

```
public Vector2 Heading
{
    get { return mHeading.RotateCopy(mOwner.Rotation); }
}

```

This seems a bit messy to me, and slower than it could be. Is there a better way to "translate" the base/owner component rotations through to whatever component I am using, like this sword?

Would using a rotation MATRIX be better? (Curretnly rotates by sin/cos) If so, how can I "add" up the matrices?

Thank you.

# Answer
I like using transformation matrices for this, because it allows me to have all sorts of complex father-child relationship between sprites such has having different relative positions, rotations, scales and origins relative to the parent, but in the end the only thing I need to do is multiply all of their matrices together and render.

I could repeat everything again but I've already written about this before on the two following questions, so look into them for more detail:

Is there a simple way to group two or more sprites, so all of them will be dependent on each other?

How to "swing" bounding box and update collision for sprite swinging a weapon?

---

I'll briefly describe the concept here though. The *basic* idea behind everything is that for each sprite in your game you'll have a single matrix encapsulating all of its transformations **relative** to the parent. In the case that there is no parent, then the transformation is simply treated as being in **world space** already.

Here's the basic interface for your sprite:

```
class Sprite
{
    Matrix RelativeTransform;
    Sprite Parent;
    List<Sprite> Children;
}

```

Then for any sprite, you can find the actual **absolute transform** with the following (somewhat recursive) expression:

```
public Matrix AbsoluteTransform
{
    get
    {
        if (Parent == null)
            return RelativeTransform;
        else return
            RelativeTransform * Parent.AbsoluteTransform;
    }
}

```

In other words, multiply your matrices together, starting from the current sprite and going all the way up to the root. This will get the absolute transform of that sprite in world space, which you can use to draw it.

As for drawing it, the first question I linked above has a method called `DecomposeMatrix` which you can use to take a `Matrix` and get some values back from it that you can use with `SpriteBatch`.
> 5 votes

# Answer
When I need children to be rotated based on whatever parent they're in, I instead have a set up where the children have offsets for translation, rotation, etc. from a central point, and that a parents origin is each child's central point as so. This way each child still has it's own central point, and the parents origin can be accessed privately in the child, because it's offset is from it's parents origin. Upon drawing, or physics or whatever, access the child through the parent, and if you don't need the child's data (it's static/purely graphical) then skip whatever step that you access the child at all.

This way you don't have to change your children's data other than is actually required, rather than updating the children every time you update the parent even when not needed.
> 0 votes

---
Tags: xna, c#, 2d, matrix, rotation
---