# Question
Title: Clarification on RenderTargetUsage in XNA 4.0
I'm trying to understand the exact meaning of RenderTargetUsage.DiscardContents. The documentation says:

> Determines how render target data is used once a new render target is set.
>
> **DiscardContents** \- Always clears the render target data.

1. Does calling `GraphicsDevice.SetRenderTarget(null)` to return to the back buffer count as setting a new render target (therefore clearing discarding any previous one)?
2. Are the contents discarded either way at the end of the frame (i.e. when the graphic device presents), or do they persist into future frames even in this mode?

# Answer
> Does calling GraphicsDevice.SetRenderTarget(null) to return to the back buffer count as setting a new render target (therefore clearing discarding any previous one)?

Yes.

> Are the contents discarded either way at the end of the frame (i.e. when the graphic device presents), or do they persist into future frames even in this mode?

In DiscardContents mode all of the render targets and the backbuffer share the same chunk of memory. So contents are not discarded they're overwritten triggering the ContentLost event. So the current rendertarget will retain its contents until its cleared/overwritten which I'm pretty sure graphicDevice.present() doesn't do.

Source: Shawn Hargreaves Blog
> 6 votes

---
Tags: xna
---


# Question
Title: Is there a technique to creating a "black hole" background in XNA?
I'm creating application in XNA 4.0 and am trying to create a specialized background. I'm familiar with the creation of a parallax scrolling background but I'd like to create a background image that appears to be draining into a hole. The issue is that I'd like the drain/black hole to exist in a variable location on the screen so it would be nice to be able to adjust the location of the background. Is using a background for this even a good idea? Maybe it'd be easier another way? Is there a term for this sort of background or is it just a modified version of parallax? Thanks!

# Answer
> 5 votes
Not sure what you are asking, if you could find a video or picture of something similar that would be great.

However, I'm assuming you want something to this.

The easiest way to do this would be with post processing. You could create a shader that would you could pass a point each draw call. It would make any pixel within a certain distance black. I would then suggest a range in which the shader would "pull" the sampling from the original texture towards the point towards the point causing the texture to stretch as if its being sucked in. Out side of the outside edge of that range the shader wouldn't effect anything.

Edit to add in info from comments on how to implement the above idea:

MSDN Sprite Effect Sample

The useful GameDev thread David Gouveia found

---
Tags: xna-4.0, sprites, graphic-effects
---


# Question
Title: Is character movement with an animated sprite controlled by the animation itself or moved manually?
How is a walking animation of a given character designed? I can see two possible ways:

The first way is to draw each frame of the animation such that, if the frames are displayed at position (0,0), the character walk but does not really move (I mean: at frame 10, the character is still at the left, upper corner of the screen). This means that one needs a way to move (translate) the frames manually.

The other way is to draw each frame such that their width grows progressively. Drawing the frame i at position (0,0) will give the impression that the character is really moving (not only walking on the same point). This way is the graphic artist that do all the job, but the animation is completely controlled by him, so he can give a specific style to the walking animation.

The first one seems to be the right way to do things, but one would need a way to say: ok, frame 0 last 50 ms at (0,0), frame 1 last 30 ms at (5, 0), frame 2 last 15 ms at (13, 0) etc...

This makes things much more complicated.

What is the best practices? What way do you usually adopt/suggest?

# Answer
The first way is the most flexible and industry standard way to handle all sprites. Walking, running, attacking, animated fruit-tiles, what-have-you. The flexibility of this method is the main reason for this.

Imagine you are making a 2D adventure/platformer. You started by having your character be able to walk slowly while charging their weapon (think Metroid) and it was initially intended that he would point in the direction he is walking. But then inspiration hits you. Maybe he should moon walk backwards instead, so that he continually points in the direction he started to charge his weapon in.

With the first option, you can easily do this. If you use the second, you need to make new sprites.

However, there are some other reasons. These spritesheets/images will be smaller in total size. When it comes time to do collision detection, you'll have an easier time of it. (Pixel-perfect collisions are slow, it will be easier to draw a box around a consistently sized sprite.) And finally, you'll be able to take advantage of existing tools that are designed for creating animated sprites in the industry standard fashion. Such as ASEPRITE or Pixen
> 2 votes

# Answer
Animated spritesheets, along with translations are the way to go. If you design your sprite classes properly, you will be able to control the flow of each animation exactly the way you want.

Consider a frame, which is essentially a Rectangle that you place at a location in your sprite sheet and "frames out" the remainder of the image. To animate a sprite, the Rectangle moves position in the sprite sheet and then displays the newly framed image to the screen. This transition is programmed and controlled by you.

By defining these transitions, you are creating your animation. The delay between each transition can be controlled, as well as other aspects of each transitions (fade in, scale, etc.).
> 2 votes

# Answer
The first is much better, people told you in other answers, but just to clear your head, yes, the frames may have different timings, frame 1 may pass with 10ms and frame 2 may pass with 30ms, but that should not be a problem.

There's a rule to gamedevelopment, that say to you to NEVER rely on the framerate to do your animations or movements. all we know, a sprite can move faster in a quad core than in a 486. Thats why you should EVER rely on delta time between frames.

How? Well, instead of doing "walk 5 pixels per frame" or doing "pass to the next frame of animation at each frame of the application" this will lead you to different gameplays in different machines. You should do: "walk 300 pixels per second" or doing "pass to the next frame of animation at each 20ms".

In pseudo code, things changes to:

```
entity.position.x += 5;
// will turn into
entity.position.x += 300 * deltaTime; //Assuming deltaTime is the time between last frame and this frame measured in float seconds.

```

and

```
animation.nextFrame();
// will turn into
float time = 0; //Declares this in your class
time += deltaTime / 1000;
if(time > 20)
{
    time = 0;
    animation.nextFrame();
}

```

of course there are other ways to doing, but this should help you to get started.
> 1 votes

# Answer
Another reason for the first method is that you won't have to adjust you collision rectangle as the sprite animates.

For example, if you use he second method, where the sprite gets wide, and you use a bounding box for collision, then you'll have to move the collision rectangle to cover the area of the sprite where the player is.

Using the first method, the sprite stays the same size, so your collision rectangle is always in the same position, relative the the sprite.
> 0 votes

---
Tags: animation, sprites
---


# Question
Title: Getting the Bounds of a 2D Cameras View with Zoom
I am using a 2D camera, which does rotations and zoom. Currently, I am using the following to get my MinX, MinY, MaxX and MaxY...

```
    public float MinX
    {
        get
        {
            return pos.X - gameEngine.screenWidth / 2;
        }
    }
    public float MaxX
    {
        get
        {
            return pos.X + gameEngine.screenWidth / 2;
        }
    }
    public float MinY
    {
        get { return pos.Y - gameEngine.screenHeight / 2; }
    }
    public float MaxY
    {
        get { return pos.Y + gameEngine.screenHeight / 2; }
    }

```

How would I now take into account Zoom? Default Zoom is 1. I think this will require Matrices, but any help is appreciated.

# Answer
**Solution with only Translation and Zoom**

It's actually quite simple to implement. The camera's view matrix transforms coordinates from world space to view space. The inverse of the view matrix transforms coordinates from view space into world space.

Using this information, you can get the bounds of your camera, whether it's zoomed or not, with this simple method (I'll use a fictional RectangleF struct as example, I assume you'll understand the logic):

```
public RectangleF Bounds
{
    get
    {
        return new RectangleF
        {
            Min = Vector2.Transform(Vector2.Zero, inverseViewMatrix),
            Max = Vector2.Transform(Game.ScreenSize, inverseViewMatrix),
        };
    }
}

```

Basically you take the top-left and bottom right-corners of the camera in view space (which are always \[0,0\] and \[screenWidth, screenHeight\]) and transform them into world space. That's your bounds.

And by the way you can get the `inverseViewMatrix` by doing a `Matrix.Invert(viewMatrix)`.

**Solution with Translation, Zoom and Rotation**

You only asked about zooming but this might come in handy too. If you try to do this with rotation mixed in, the process changes a little. In this case instead of only transforming the top-left and bottom-right corners, you need to transform all four corners, and then find the minimum and maximum X and Y values to create your bounding box. Something like:

```
Vector2 tl = Vector2.Transform(Vector2.Zero, inverseViewMatrix);
Vector2 tr = Vector2.Transform(new Vector2(Game.ScreenSize.X, 0), inverseViewMatrix);
Vector2 bl = Vector2.Transform(new Vector2(0, Game.ScreenSize.Y), inverseViewMatrix);
Vector2 br = Vector2.Transform(Game.ScreenSize, inverseViewMatrix);
Vector2 min = new Vector2(MathHelper.Min(tl.X, MathHelper.Min(tr.X, MathHelper.Min(bl.X, br.X))), MathHelper.Min(tl.Y, MathHelper.Min(tr.Y, MathHelper.Min(bl.Y, br.Y))));
Vector2 max = new Vector2(MathHelper.Max(tl.X, MathHelper.Max(tr.X, MathHelper.Max(bl.X, br.X))), MathHelper.Max(tl.Y, MathHelper.Max(tr.Y, MathHelper.Max(bl.Y, br.Y))));
RectangleF bounds = new RectangleF {Min = min, Max = max};

```

What this does is basically find the smallest AABB that can completely fit the OBB that would be formed by the four corners of your camera.
> 4 votes

---
Tags: c#, camera, matrix
---


# Question
Title: How to get mouse position relative to the map?
I'm creating a game in XNA similar to Minecraft - Minecraft 2D

It looks like this

Here's how it works:

* All blocks are generated once with fixed x,y coordinates and just re-drawn.

```
    //generate world
    for (int i = 0; i < 25; i++)
    {
        blocks.Add(new Block("top", i * 32, 32 * 7, Color.White));
        for (int j = 8; j < 20; j++)
        {
            blocks.Add(new Block("dirt", i * 32, 32 * j, Color.White));
        }
    }

```
* When user clicks on a block, I just browse through all blocks and check whether block exists.

```
if ((mouseCoordinate.X - (mouseCoordinate.X % 32)) == block.x && (mouseCoordinate.Y - (mouseCoordinate.Y % 32)) == block.y) {
      //destroy block
}

```
* Currently, without any camera movements, everything works. When I move my camera just about 32px to the right, for example, it's all broken. I can't do previous step anymore.
* What I need: I need to get mouse position relative to the map, not to the game window. How can I get mouse position relative to the map? Basically, I want mouse position 0,0 on the point I have circled here

How do I calculate it?

EDIT: here's my camera class (yes, Matrix)

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Reflection;
namespace MojePrvniHra
{
    public class Camera2d
    {
    protected float _zoom; // Camera Zoom
    public Matrix _transform; // Matrix Transform
    public Vector2 _pos; // Camera Position
    protected float _rotation; // Camera Rotation

    public Camera2d()
    {
        _zoom = 1.0f;
        _rotation = 0.0f;
        _pos = Vector2.Zero;
    }// Sets and gets zoom
    public float Zoom
    {
        get { return _zoom; }
        set { _zoom = value; if (_zoom < 0.1f) _zoom = 0.1f; } // Negative zoom will flip image
    }

    public float Rotation
    {
        get { return _rotation; }
        set { _rotation = value; }
    }

    // Auxiliary function to move the camera
    public void Move(Vector2 amount)
    {
        _pos += amount;
    }
    // Get set position
    public Vector2 Pos
    {
        get { return _pos; }
        set { _pos = value; }
    }

    public Matrix get_transformation(GraphicsDevice graphicsDevice)
    {
        _transform =
          Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
                     Matrix.CreateRotationZ(_rotation) *
                     Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
                     Matrix.CreateTranslation(new Vector3(graphicsDevice.Viewport.Width * 0.5f, graphicsDevice.Viewport.Height * 0.5f, 0));
        return _transform;
    }

    }
}

```

and here's how I start my `spriteBatch`

```
       spriteBatch.Begin(SpriteSortMode.BackToFront,
                BlendState.AlphaBlend,
                null,
                null,
                null,
                null,
                cam.get_transformation(graphics.GraphicsDevice));

```

# Answer
**Solution**

Is your camera simulated using a view matrix? If so, all you need to do is:

```
Vector2 worldPosition = Vector2.Transform(mousePosition, Matrix.Invert(viewMatrix));

```

And if you're not using a view matrix... you should :-)

**Explanation**

The view matrix transforms coordinates from world space into view space. The *inverse* of this matrix does the *opposite* \- it transforms coordinates from view space back into world space.

Since your mouse coordinates are defined in view space, all you need to do is transform them with the *inverse view matrix* to convert them into world space.
> 13 votes

# Answer
The concept here is unprojecting a mouse coordinate to eye-space. When dealing with graphics, there are several different coordinate systems used to represent objects. I'll explain all of them, but the way you have set your rendering up cancels the need for the coordinate spaces:

* Everything is generally defined by vertices relative to (0, 0). This is called local space.
* If you want to position an object in the world, you need to convert local space to world space. You do this with what is called a **model matrix**, which allows for movement, rotation, and scaling of the object. The way you've set up your rendering does this, or a simple version of this by just providing the X and Y location of the `Block` in the world.
* If you want to move around the world, you need to convert world space to eye space. This is done with a **view matrix**. You can move, rotate, and scale the camera in any way you want. In your case, you're either using a view matrix or just storing the location of the camera and offsetting everything by that position.
* DirectX uses a default coordinate system of -1 to 1 on the X and Y axes (0 to 1 on the Z, but that's not important). Everything that is rendered must exist within that range, and to convert to that coordinate system, you need one last transformation - the **projection matrix**. In this case, you've set up your projection matrix to convert pixel coordinates to the default coordinate system. In this case the projection matrix doesn't make a difference when unprojecting, as it'll just give you the same mouse coordinate back.

On to the actual solution, you've removed the need for the model and projection matrices, so you can set up a view matrix from your camera position if you don't already have one. From there you're just using `Vector2.Transform` as suggested by the previous answer.

If you want the most direct solution that you can implement very quickly and without matrices, you can just offset your mouse coordinates by the camera position before aligning it to the nearest block like this:

```
Vector2 cameraPos = /*The position of your camera*/;
Vector2 clickCoord = mouseCoordinate + cameraPos;
if ((clickCoord.X - (clickCoord.X % 32)) == block.x && (clickCoord.Y - (clickCoord.Y % 32)) == block.y) {
      //destroy block
}

```
> 3 votes

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


title: OpenGL 3 and the Radeon HD 4850x2

text:
# Question
Title: OpenGL 3 and the Radeon HD 4850x2
A while ago, I picked up a copy of the OpenGL SuperBible fifth edition and slowly and painfully started teaching myself OpenGL the 3.3 way, after having been used to the 1.0 way from school way back when. Making things more challenging, I am primarily a .NET developer, so I was working in Mono with the OpenTK OpenGL wrapper. On my laptop, I put together a program that let the user walk around a simple landscape using a couple shaders that implemented per-vertex coloring and lighting and texture mapping. Everything was working brilliantly until I ran the same program on my desktop.

Disaster! Nothing would render! I have chopped my program down to the point where the camera sits near the origin, pointing at the origin, and renders a square (technically, a triangle fan). The quad renders perfectly on my laptop, coloring, lighting, texturing and all, but the desktop renders a small distorted non-square quadrilateral that is colored incorrectly, not affected by the lights, and not textured.

I suspect the graphics card is at fault, because I get the same result whether I am booted into Ubuntu 10.10 or Win XP. I did find that if I pare the vertex shader down to ONLY outputting the positional data and the fragment shader to ONLY outputting a solid color (white) the quad renders correctly. But as SOON as I start passing in color data (whether or not I use it in the fragment shader) the output from the vertex shader is distorted again. The shaders follow. I left the pre-existing code in, but commented out so you can get an idea what I was trying to do. I'm a noob at glsl so the code could probably be a lot better.

My laptop is an old lenovo T61p with a Centrino (Core 2) Duo and an nVidia Quadro graphics card running Ubuntu 10.10 My desktop has an i7 with a Radeon HD 4850 x2 (single card, dual GPU) from Saphire dual booting into Ubuntu 10.10 and Windows XP. The problem occurs in both XP and Ubuntu.

Can anyone see something wrong that I am missing? What is "special" about my HD 4850x2?

```
string vertexShaderSource = @"
#version 330

precision highp float;

uniform mat4 projection_matrix;
uniform mat4 modelview_matrix;
//uniform mat4 normal_matrix;
//uniform mat4 cmv_matrix;  //Camera modelview.  Light sources are transformed by this matrix.
//uniform vec3 ambient_color;
//uniform vec3 diffuse_color;
//uniform vec3 diffuse_direction;

in vec4 in_position;
in vec4 in_color;
//in vec3 in_normal;
//in vec3 in_tex_coords;

out vec4 varyingColor;
//out vec3 varyingTexCoords;

void main(void)
{
  //Get surface normal in eye coordinates
  //vec4 vEyeNormal = normal_matrix * vec4(in_normal, 0);

  //Get vertex position in eye coordinates
  //vec4 vPosition4 = modelview_matrix * vec4(in_position, 0);
  //vec3 vPosition3 = vPosition4.xyz / vPosition4.w;

  //Get vector to light source in eye coordinates
  //vec3 lightVecNormalized = normalize(diffuse_direction);
  //vec3 vLightDir = normalize((cmv_matrix * vec4(lightVecNormalized, 0)).xyz);

  //Dot product gives us diffuse intensity
  //float diff = max(0.0, dot(vEyeNormal.xyz, vLightDir.xyz));

  //Multiply intensity by diffuse color, force alpha to 1.0
  //varyingColor.xyz = in_color * diff * diffuse_color.xyz;
  varyingColor = in_color;

  //varyingTexCoords = in_tex_coords;
  gl_Position = projection_matrix * modelview_matrix * in_position;
}";

        string fragmentShaderSource = @"
#version 330
//#extension GL_EXT_gpu_shader4 : enable

precision highp float;

//uniform sampler2DArray colorMap;

//in vec4 varyingColor;
//in vec3 varyingTexCoords;

out vec4 out_frag_color;

void main(void)
{
  out_frag_color = vec4(1,1,1,1);
  //out_frag_color = varyingColor;
  //out_frag_color = vec4(varyingColor, 1) * texture(colorMap, varyingTexCoords.st);
  //out_frag_color = vec4(varyingColor, 1) * texture(colorMap, vec3(varyingTexCoords.st, 0));
  //out_frag_color = vec4(varyingColor, 1) * texture2DArray(colorMap, varyingTexCoords);
}";

```

Note that in this code the color data is accepted but not actually used. The geometry is outputted the same (wrong) whether the fragment shader uses varyingColor or not. Only if I comment out the line varyingColor = in\_color; does the geometry output correctly. Originally the shaders took in vec3 inputs, I only modified them to take vec4s while troubleshooting.

# Answer
NVidia has their own shading language called Cg, and their drivers have a common compiler between Cg and GLSL as GLSL is considered Cg compatible. Because of this, what will compile on an NVidia card may not be pure GLSL as defined by the spec. The ATI/AMD GLSL compiler is extremely strict about sticking to the spec.

Try running your shaders through AMD GPU ShaderAnalyzer to see what types of errors you will receive on ATI cards. As a bonus the tool will show you the compiled assembly of your shader.
> 2 votes

---
Tags: opengl, .net, glsl, mono
---


# Question
Title: GluUnproject works, but only when the camera is not rotated
I am working on a very basic 3D program, my first one using OpenGL. What I am trying to do is trace a ray from the mouse's location on click which works, but only when the camera is not rotated. When the camera is rotated, the unproject treats it as if it was not.

What am I doing wrong?

The code for unproject:

```
Coord3<GLdouble> Display::GetOGLPos(uint16_t x, uint16_t y)
{
    GLint viewport[4];
    GLdouble modelview[16];
    GLdouble projection[16];

    Coord2<GLfloat> window_location;
    Coord3<GLdouble> resultant_ray;

    glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
    glGetDoublev(GL_PROJECTION_MATRIX, projection);
    glGetIntegerv(GL_VIEWPORT, viewport);

    window_location.x = (float)x;
    window_location.y = viewport[3] - (float)y;

    gluUnProject(window_location.x , window_location.y, 1.0f, modelview, projection, viewport, &resultant_ray.x, &resultant_ray.y, &resultant_ray.z);

    return resultant_ray;
}

```

The display code:

```
void Display::Render()
{
    if(!dirty)
    {
        return;
    }

    glTranslatef(camera.location.x ,camera.location.y, camera.location.z);

    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

    glRotatef(camera.angle.y, 1, 0, 0);
    glRotatef(camera.angle.x, 0, 1, 0);

    glCallList(cube);

    glColor3ub(0, 0, 255);

    glBegin(GL_LINES);
    glVertex3f(0,0,0);
    glVertex3f(mouse_click.x, mouse_click.y, mouse_click.z);
    glEnd();

    glLoadIdentity();

    SDL_GL_SwapBuffers();

    dirty = 0;

    SDL_Delay(33);
}

```

# Answer
It might be because you're clearing the modelview matrix at the end of `draw()` with `glLoadIdentity();` Try doing the transformations again at the beginning of `GetOGLPos` before you call `glGetDoublev()` for the matrices, then loading the identity matrix afterwards.
> 1 votes

---
Tags: opengl
---


# Question
Title: What language and tools are good to start with for Linux game development?
I would like to start learning about game development and I would like to do it using Linux. My main experience has been with Java and a bit of C++, but that was for applications and not games.

Now that I want to try with gaming, I'm wondering which IDE/language should I use in Linux, whether I should go with C++ and compiling files manually at the beginning, or maybe continue with Java/Eclipse, also I think I can use Eclipse with C++, I have also started reading about Python...

I was thinking in starting with the typical "Tetris" just to understand how a game works internally, and I think I can achieve that with all the previous options, but what do you recommend me or how have you started game developming under Linux?

# Answer
If you've never done game programming before, you should probably start with 2D. SDL is a pretty straightforward library with nice bindings for C++. You can use whatever editor / IDE you like, but I'm a big fan of code::blocks.

There are finally some nice game engines for Java, (Java Monkey Engine) but Java kind of gets in the way sometimes. I like Java (I've taught it for years) but it always seems kind of clunky to me as a game development environment.

I'm a huge fan of Python and pyGame. (PyGame is simply SDL with bindings for Python.) You can build a really nice 2D game quite quickly. Python is quite easy to learn, and it tends to let you focus more on the game programming rather than memory and pointer issues. It's true that Python code isn't quite as fast as natively compiled C++ code, but it's more than fast enough, and the easier coding and debugging will often make up for the difference. If you find a critical section that Python simply cannot handle, you can write that section in C/C++ and use it as a module.

I teach a game development class, and I've switched languages several times. I'm very happy with Python as a language to teach game development with.

Best of luck to you.
> 4 votes

# Answer
Regarding C++, a very cool IDE is QtCreator. On Linux, chances are that you have Qt already in your system, if you have KDE applications installed, even if running Gnome.

If you want to try other scripting languages for simple games, I've had a very pleasant experience with Löve2D, a game engine for Lua. It's very easy to get something fun made in no time.
> 1 votes

# Answer
If you want to create high-performance real time games, or you want to get into professional game development, then only C or C++ are practical language choices currently.

This is because a) They can create fast, efficient code using small amounts of memory (many high level languages do not give you the ability to explicitly control memory allocation, which makes it difficult to optimise cache usage or fit data in the limited memory used by many systems). b) They are the industry standards that are used by the vast majority of AAA games. Particularly C++, though the languages are reasonably similar (when it comes to the ways they are used in Game Development anyway).

For a framework, I would advise learning OpenGL. It might be a little bit more complicated than some systems, but it's very powerful and widely used, and your knowledge can scale up from Pong all the way up to Unreal. There are plenty of good tutorials, just google for 'OpenGL tutorial'.

To make things slightly easier, you can use an OpenGL wrapper framework (I recommend GLFW - http://www.glfw.org/ \- though GLUT is also popular).

As much as possible, try to write the code yourself rather than relying on pre-built frameworks. This will teach you the basics of game update loops, input processing, rendering, etc. That will stand you in great stead for building more detailed projects later.
> 1 votes

# Answer
I consider Linux in itself a pretty neat development environment. Most distributions have everything you need to develop c/c++ apps, just invest some time learning gcc, gdb, vim and a decent build system like Make, CMake or Scons.

If you are using c/c++ then SDL would be a good starting point, library wise - because you will find a huge amount of tutorials for it. For python I found pyglet to be an excellent library, although i haven't used it for 2 years. Just keep in mind that deployment of a python app is not "that" easy..
> 1 votes

# Answer
You should definitely go with C++. Using it will give you access to the most libraries, and depending on the what your project is will give you good flexibility and performance.

A good place to start is with LazyFoo's SDL tutorials. They can be used for a variety of different projects but are easy to understand at any skill level.
> 1 votes

# Answer
I use vim and highly recommend it - it's a very powerful text editor designed to help you write code quickly. It has a pretty steep learning curve, though (after installing it, run 'vimtutor' to get a quick walk through). I've been using it for 8 years now and couldn't imagine using anything else.

I'd also suggest not jumping into an IDE immediately. In my experience, IDEs are clunky and get in the way (especially while you are configuring a new project). I've kept Eclipse/CDT around as it is indispensable as a debugger, though.

If you've got C++ experience, I'd stick with that. As others have mentioned, SDL is a great way to get started -- you can't go wrong there.

Tetris was the first game I made and probably isn't a bad way to go, but you might also consider something like a 2d platformer or a 2d top-down adventure game.
> 1 votes

# Answer
If you want to use C++, I can highly recommend KDevelop4. They've made a lot of improvements that make it a very good IDE. Grab SFML or SDL and get hacking.

I also highly recommend good old Vim or Emacs for any language.

But if you want to just kick some code about, you might try Python+PyGame. You can get simple games up and running very quickly, and you don't need a fancy IDE.

I haven't looked at them, but it looks like Ruby also has a bunch of frameworks you can try, if you want to learn Ruby.
> 0 votes

# Answer
I'd strongly suggest jMonkeyEngine if you have Java skills - it's a very good general purpose, open source 3D game engine.

It's fully cross platform (all it really needs is OpenGL support and a JVM) so will run on Linux but also maintain portability to Windows or Mac etc.
> 0 votes

---
Tags: tools, linux
---


# Question
Title: Efficient way of detecting a touched object in a game?
Imagine a Sims-like 2D game for a touch based mobile phone where one can interact with virtually any object in the scene.

**How can I efficiently detect which object is being touched by the player?**

In my short experience, looping through all the visible objects in the scene and checking if they're touched has so far done the job, but when there may be many many moving objects in the screen that sounds kind of inefficient isn't it? Keeping the visible moving objects list can consume time in itself as one may have to loop through all of them each frame.

Other solutions I've thought are:

Spatial hashing. Divide the screen as a grid and place the visible objects in the corresponding bucket. Detection of the clicked object is fast but there's additional overhead for placing the objects in the correct bucket each frame.

Maintaining a quad-tree. Moving objects have to be rearranged all the time, the previous solution looks better.

What is usually done in this case?

# Answer
> 7 votes
I'd recommend **profiling first** and check if the touching check really is a bottleneck.

Test with the maximal amount of objects that your game will use as a final product and see if you get frame drops.

If it is in fact a bottleneck, I'd say go with the spatial hasing option and see if it gets better this way.

But this is just my personal opinion. I'd say test and see if you really need to optimize, and if you do, check for alternatives.

# Answer
> 2 votes
To me, this suggests an off-screen buffer with a specialized render of the view on the screen. Each object is entirely one colour (no lighting calculations etc) which uniquely identifies the object. Z buffering used as for a normal render. Maybe lower resolution than the main screen render - at the very least antialiassing would be bad, so no need to render higher resolution than the screen.

This *may* be a way to offload most of the work to the graphics hardware.

Warning - I'm not an experienced game developer - this is just an idea, it may not be possible.

# Answer
> 0 votes
You can create a grid of many squares, attend to each one what static objects are visible trough an Array before the game start, then at each frame see to which square the player belong and draw the objects. Every object has an ID so the drawing is ID based:

```
int x = getSquare().X;
int y = getSquare().Y;
int n = Square[x][y].Number_of_objects;
for(int i = 0; i < n; i += 1){
    Draw(StaticObjet[Square[x][y].Object[i].Id]);
};

```

---
Tags: 2d, java, input, monotouch
---


title: Heightfield terrain in ASCII games?

text:
# Question
Title: Heightfield terrain in ASCII games?
Is there a good way to represent variable terrain using heightfields (or heightmaps) in an ASCII game such as a Roguelike?

# Answer
> 5 votes
ASCII games are really nothing more than just tile-based games that use character glyphs instead of pictures of what they really represent. In general, height fields do not work well in tile-based games. Not unless it's in some kind of perspective view. Height fields generally are used for 3D terrain.

When your palette of tiles is limited to whatever characters happens to be in the ASCII character set and the particular font to be displayed, you have to put forth some effort in comparing the different glyphs to see which ones look good "in front of" the others. In general, when it comes to ASCII art, the glyphs with less stuff in them are darker and can thus represent farther away terrain.

Or you can just ditch the ASCII art and put together a real black-and-white tilemap. You're more likely to get good results and it really doesn't require that much more work than ASCII tilemaps.

# Answer
> 6 votes
This will really depend on your requirements. How many levels of height are there. Just a few? Hundreds?. Top down? First person? Limit of 1 character per tile or can you use several. What is the terminal size 80x23? or is it going to be resizable. On devices with limited CPU power like a graphic calculator or more beefy modern computers. Text in console textmode or are you ok with using graphics for the actual rendering of the text.

Is it important to be able to tell the difference between level 3 and level 1 or just that one level is above the other.

If it's only important that one is seen as being higher than the other then everything could be 'flat' and you just draw ramps up ledges like in a SNES RPG. This requires more than 1 tile to be used since you will need to have at least impassable bits representing stuff facing the camera and the edges you can fall off.

Another possibility is some kind of depth slice system. Where you don't draw the levels above the level you are currently one and just have them black since you can see them from your position. You might 'fade' out the levels below. You could even go further and use raytracing for a field of view (so you can see past something like a pillar, see ASCII portal for a similar kind of ray-tracing but it's only used when looking through the portals).

Are you using raw oldskool ASCII (only 127 characters, It's almost identical standardized successor ISO/IEC 646). ANSI/Windows-1252 such as on Microsoft platforms. Some kind of Extended ASCII. MS-DOS style extended ASCII codepage 437. Or actually Unicode (which allows all that and much more and is supported in most places now).

If it's either of the last 2 then you could look at using the following box-drawing characters "░▒▓█"

```
████████████
██▓▓▓███████
█▓▓▓▓▓▓▓▓▓▓█
█▓▓▒▓▓▓▓▓▓▓█
█▒▒▒▒▒▒▒▒▒▒▒
█▒░░░░▒▒▒▒▒█
█░░ ░░░░░░██
█        ███
████████████

```

Also are you using colours at all? You might be able to mix in gradient grays or something.

You could use some kind of basic projection:

```
.     ______       _____
|\   /|....|       |...|
|.\_/.|____|       |___|
\ .|. /    |       |   |
 \ | /     |_______|   |
  \|/      |.......|   |
           |_______|   |
       @               |
_______________________|
.......................|
_______________________|__

```

You could look at some isometric ascii art.

Finally you can look at actually rendering 3D graphics in ASCII. One technique is to actually draw ASCII lines or polygons. Alternatively if you have a large enough window size something like a grayscale to ASCII conversion is do able, where you just render using something like OpenGL then convert. See either or ASCII/Textmode Quake . In order to be viewable these require things like larger terminal sizes, frequent updates and decent CPU power.

Finally if your just doing ASCII for artistic reasons. You could look at projecting the characters themselfs into 3D. So you characters that are higher up would actually be higher up (ie appear larger closer to the camera). You could even do things like for of depth of field blur and so on.

# Answer
> 1 votes
It depends on what you want to use to display your map. If height is an important part of it, you may want to switch away from a curses style output to something more like SDL or OpenGL (unless you plan on using a central server or the likes). Also, these don't preclude you from using ASCII symbols to represent everything else either.

Personally for my project, I'll be using ASCII symbols the represent the map, and an OpenGL rendered gradient map to display the height of the mapped terrain.

---
Tags: heightmap, roguelikes
---


title: Make object follow mouse angle?

text:
# Question
Title: Make object follow mouse angle?
what I'm trying to do is make the paddle follow the mouse position(red dot).
I know how to rotate the paddle relatively to the center of the screen, but I'm not sure how to determinate the coordinates.

thanks.

# Answer
> 3 votes
From what I understand, you want to have the paddle be at a point on the circle nearest the mouse cursor. Here's the general way of calculating that point:

* We know for a fact that the shortest distance between a point and a circle must go through the circle's center, so a vector can be created from the directed line segment starting at the center of the circle and ending at mouse cursor.
* From here we need to calculate the angle between the X unit vector and our vector. There are many ways of doing this, but the one I prefer (if your 2d vector class has a perpendicular dot product method) is `angle = atan2(perpDot(v1, v2), dot(v1, v2))`. Using atan2, we get an angle in the range (-pi, pi\].
* Next we need to get the actual location of that angle on the circle, which is as simple as `<cos(angle), sin(angle)>`.
* If your circle isn't a unit circle (radius != 1), scale the vector by the radius. If your circle isn't centered at (0, 0) add it's center as a vector to the position vector you just calculated.

# Answer
> 4 votes
The simplest way would be to make your paddles origin at the center of the circle. Then you just need to calculate the angle and you're done (your paddle origin, or center position should be at the circle center and the paddle itself should be to the right of the circle as starting position).

Something like this:

```
// calculate delta from circle center to mouse position
var dx:Number = mouseX - circleCenterX;
var dy:Number = mouseY - circleCenterY;

// get the rotation (in radians)
var radians:Number = Math.atan2(dy, dx);

// then we can simply apply the rotation to the paddle,
// but we have to convert to degrees first
paddle.rotation = radians * 180 / Math.PI;

```

If you want to have the paddle origin at the center of the paddle itself, then you can do the following to get a point that's always on the circle (the code to obtain the rotation will be the same as above):

```
// using the delta variables from the code snippet above
var point:Point = new Point(dx, dy);

// normalizing the vector and scaling it to the circle radius will give us
// a point lying on the circle
point.normalize(circleRadius);

// add the circle center to the point to get "world coordinates"
point.x += circleCenterX;
point.y += circleCenterY;

```

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


# Question
Title: XNA UV Mapping flipping the Texture every second time
I am making a tile based game. Recently I moved to drawing tiles as primitives to speed up things and also allow for easier lighting (Vertex Shader).

I then took it a step further and made some calculations to "merge" together tiles into the same primitive to gain even more performance, and to get around UV texture problems I simply did this...

```
if (!top)
{
    //Adds the top vertices
    thisquad.Vertices[0] = new VertexPositionTexture(new Vector3(new Vector2(p.X, p.Y), 0), new Vector2(0, 0));
    thisquad.Vertices[1] = new VertexPositionTexture(new Vector3(new Vector2(Tile.Size + p.X, p.Y), 0), new Vector2(1, 0));
    top = true;
}
//Extends the bottom vertices
thisquad.Vertices[2] = new VertexPositionTexture(new Vector3(new Vector2(p.X, Tile.Size + p.Y), 0), new Vector2(0, currentquadtilecount));
thisquad.Vertices[3] = new VertexPositionTexture(new Vector3(new Vector2(Tile.Size + p.X, Tile.Size + p.Y), 0), new Vector2(1, currentquadtilecount));
currentquadtilecount++;

```

With currentquadtilecount starting at 1, if a tile is floating on its own it will display the texture properly, but for every second tile that merges, the texture is flipped. As shown below...

What am I doing wrong? Is this even the right way to do this??

Twitchy

# Answer
> 2 votes
I'm almost sure this is because you're using `TextureAddressMode.Mirror` instead of `TextureAddressMode.Wrap`.

Change the value in the sampler state *before* rendering the primitives. I think it should be something like:

```
GraphicsDevice.SamplerStates[0].AddressU = TextureAddressMode.Wrap;
GraphicsDevice.SamplerStates[0].AddressV = TextureAddressMode.Wrap;

```

---
Tags: xna, uv-mapping
---


# Question
Title: Is there a good guide on terrain topography creating?
I want to create a map for my level, and to make it look realistic from topographical pont of view. Is there anything that you can recommend?

**Edit:** I want to create a 3D map of islands, sea, volcanoes, shores, that will look natural.
Suppose that I want to write the map generator by myself.
Are there any resources on natural land topography?
Examples :

* The sea level should be the same anywhere.
* Sand should be near the shore.
* There is no way that there will be a huge mountain in the middle of the shore

# Answer
The best resource I've ever read on this subject is the following article written by Amit Patel:

http://www-cs-students.stanford.edu/~amitp/game-programming/polygon-map-generation/

Here's a 2D picture of this technique:

And a 3D version of it:

I think the results are stunning. You can also try a demo here. All credit goes to Amit of course.
> 4 votes

---
Tags: maps, topography
---


# Question
Title: When connecting a physics engine to another engine, should you do all your logic in the units used by the physics side or the rendering side
I'm currently intergrating pygame and pyBox2D, and am wondering which side is best to try to keep to in terms of game units of size.

Box2D is Meters

PyGame is Pixels

At the moment I am thinking I will keep everything on the box2D side where it makes sense, and then just use a scaling method to turn those numbers into pixel locations. But sometimes I will want to detect something in pixels (mouse location) and have this relate back to the location in the Meters side. Obviously I can use the reverse scaling to get that point, but I was wondering if there are any tips about this?

In order to make the scale easier, I have aligned the box2d world horizonal 0+ and vertical 0+ to match the location of pygame, which takes top left as 0,0 . First attempt I was doing something crazy with 0,0 being in the middle of my pygame world. Seems no reason not to calibrate the Box2D world to match the pygame rendering one to some degree.

Any thoughts or tips?

# Answer
> 4 votes
Like Tetrad said, it's a really good idea to constrain *all* of your conversions to a single place on your code. This will ensure consistency across the game.

I'm not familiar with Python, but in C# I'd create a small helper class to help me with this. For instance:

```
public static class UnitsConverter
{
    public static float M2P(float meters) { return meters * _scale ; }
    public static float P2M(float pixels) { return pixels / _scale ; }
    public static void SetScale(float scale) { Scale = _scale ; }
    private static float _scale = 100f;
}

```

And then use it everywhere:

```
UnitsConverter.SetScale(1000f);
float screenX = UnitsConverter.M2P(entity.X);
entity.X = UnitsConverter.P2M(mouse.X);

```

And I'd like to reinforce again (in case it passes unnoticed in the comments) that you should **never ignore Box2D's scale definition and treat pixels as meters**. The documentation clearly says:

> Box2D is tuned for MKS units. Keep the size of moving objects roughly between 0.1 and 10 meters. You'll need to use some scaling system when you render your environment and actors. The Box2D testbed does this by using an OpenGL viewport transform. DO NOT USE PIXELS.

And as someone who's made this mistake before (and it took me a long time to figure out what the problem was) I can tell you that the problems it creates start showing up the most obscure ways.

If I remember correctly, everything moved sluggishly no matter how much force I applied, and collisions didn't look natural either. Changing to a more reasonable scale solved the problems completely.

# Answer
> 1 votes
The only tip I have is to make the conversion in one place and only one place. If you start having to do inline conversions all over the place from one coordinate system to another you're going to run into a whole host of problems.

# Answer
> 1 votes
My opinion is to use the Box2D units over the pixel of none of the two.

You **Have** to use a non pixel based units because of the engine implementation issues and "have" to use the pixel unit because of rendering issues: neither of them (may) constitutes the reality of that you intend to represent.

So the answer: use the box2D unit system as "user" system if it make sense for you; you will store this kind of values in your entities, your graphics facilities knows this and will convert in pixel when necessary.

If the box2D units do not make sense then use a metric that does. Again, store that values everywhere is necessary: your graphic engine knows and does its conversion - your phisic engine knows and does its conversions.

*Edit:*

Graphical user input processing (clicks & touches) has to be done in the graphics subsystem and should return the position in a consistent way i.e. the unit system you choose.

# Answer
> -2 votes
Until a satisfactory explanation for the systems odd behaviour has been found I will simply advice against using Box2D.

---
Tags: physics, box2d, rendering, pygame
---


# Question
Title: Box2D/Farseer - Moving fixtures on a Static Body
I am attempting to create a Pool of Fixtures, in order to reduce memory consumption. My problem is that when I attempt to return a Fixture to the Pool and re-assign its position on the Parent Body, once it is repositioned the Fixture no longer provides any collision response with other world objects.

It seems that if you want to move a Fixture on a Static body, it needs to be destroyed and re-created. This method doesn't allow me to use my Pool however.

Does anyone know if it is possible to move a Fixture on a Static Body? I do not want to move the Body, but the Fixtures attached to it.

# Answer
> 3 votes
Velcro Physics (formerly Farseer Physics) is open source.

> /// Warning: You cannot reuse fixtures.

If you still want to do this, then try to reproduce some of the steps that the `Fixture.RegisterFixture()` private method does.

---
Tags: xna, box2d, body
---


# Question
Title: Why is my character not moving when applying an acceleration to it?
I'm having issues with my character in terms of gravity and the character bouncing up and down. You can find more information about it in the link below.

Character bouncing off ground due to gravity

I thought the answer below fixed it unfortunately it didn't after doing some more digging through the original platformer example on the app hub.

Platformer Starter Kit

The bouncing issue was resloved in the following way in the original.

The velocity would be added to the position

```
position += velocity;

```

Then the position would values would be even out.

```
position = new Vector2((float)Math.Round(position.X), (float)Math.Round(position.Y));

```

The x movement is below

```
accerlation = 0.046875f

velocity.X = velocity.X + accerlation;

```

and gravity is being added like so

```
private float gravity = 0.21875f;

velocity.Y = velocity.Y + gravity;

```

The issue is that the values are so small that once they've been added they are taken off again resulting in the character not moving. What is the best approach to solving this issue ?

# Answer
The reason why your character is not moving is because your acceleration values are just too small. I recommend taking this course of action:

**Step 1) A few improvements to the physics code**

First make your physics code based time-based instead of frame-based. This simply means that where you used to have something move X units per frame, now it will be moving X units *per second* instead. Just multiply the elapsed time when calculating the velocity and position!

You could optionally also use velocity verlet over euler integreation as presented on this article for an extra bit of stability.

I'll leave it out for this example though:

```
// This value will be used as your variable time step
float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;

// These values will have to be tweaked for your game
float acceleration = 1f;
float gravity = 1f;
Vector2 maxVelocity = new Vector2(50f, 50f);

// Apply accelerations
velocity.X += acceleration * dt;
velocity.Y += gravity * dt;

// Limit the maximum velocity so you don't accidentally go back in time
velocity = Vector2.Clamp(velocity, -maxVelocity, maxVelocity);

// Apply velocity
position += velocity * dt;

```

**Step 2) Tweak the acceleration/gravity values until you get something that feels right**

The next step is finding the best values for your gravity, acceleration and maximum velocity variables.

You could start with reasonable values near what you expect them to be by definition (remember that you're dealing with units per second now, not per frame).

Then temporarily add an option to your game to tweak the values during gameplay. This will let you search for the best values while trying it out at the same time. Once you find the best values, hardcode them or put them into a configuration file.
> 0 votes

---
Tags: xna, physics, platformer
---


# Question
Title: In game level editor using AIR or stand alone app using Java or C#
I'm in the process of choosing technologies to build the level editor of a Flash RPG game.

On one side I can use AIR and build a ingame level editor that's probably going to give the best result. The problem is, I think it will be very hard, I don't have good memories using the UI libraries of AS3. I think that would take at least 3 more times (to build the editor) than the other approach.

Or I can use some mature set of tools to build the editor, like the ones commonly used with C# or Java.

The question is: Is it worth the trouble to build the editor in AIR? Or using a stand alone editor is just fine?

EDIT: Me and my team are the only people using this editor.

# Answer
As David stated it is a personal preference but there are some practical questions as well.

It is also a question of if an how you can create an in-game editor without changing your game code (which I think is not a good idea unless the player should be enabled to use the editor as well) and/or having to implement everything twice. Separating game and editor and having the actual game logic only in one place is a good thing!

But what I also find very important is to have at least some kind of preview/in-game view to see how changes reflect in the actual game. I am working on an XNA game where the editor hosts an XNA component and all the designer stuff is done in WPF. In your case I would suggest doing something similar using some browser control to load/refresh your actual game from within the editor. Continuously pressing Alt+Tab does not make your design work easier ;-)
> 0 votes

# Answer
If you are building an editor for a Flash game, it might make sense to build the game editor in Flash/AIR. That way you wouldn't need to port/rewrite the core logic/rendering code from Flash to C#/Java.

That said, if it were an **in-game** editor, wouldn't the editor be of the same platform as the game, eg. Flash?
> 1 votes

# Answer
That's a bit subjective. It's going to depend mostly on how familiar you are with each of the technologies. And I think the deciding factor would also be, do you really need the level editor to be available *in game*? Is the general user supposed to have access to the editor too? If you're the only one that's going to use it, don't think twice, just go with the technology you're more familiar working with, even if it's a standalone editor. Personally, I'd go the standalone editor route, but that's just *my* preference.

With that said, there are *some* advantages to building the editor *in game*. For one, you can use the codebase that you alredy built for the game to aid you with the editor. And you can more easily switch between normal gameplay and level editing on the fly. Is it worth the extra effort? That's up to you.
> 0 votes

---
Tags: c#, java, flash
---


title: Fixing Slow XNA Game

text:
# Question
Title: Fixing Slow XNA Game
I'm kind of new to XNA (and games in general). I'm trying to make a young relative of mine (10yo) a simple fun game where he is the main character. I'm down to the wire (I have to get it to him by tomorrow and wont have time to work on it at all tomorrow, which means I have to finish it tonight). Everything was tight as it is (I'm kind of close to being finished, but not really). Everything was going pretty smoothly until a minute ago when I asked monsters and finished the level map data.

Here is a copy of what the map data looks like:

Its only 16x100. Basically, each color represents an object already specified in other parts of the game. I'm doing this for simplicity. Parsing the image itself happens nearly instantaneous so don't yell at me for doing it this way. The maps are pretty straight forward and don't need any real optimization.

Now, my first guess was, having this many monsters causes maaaaaaajor lag... (notice the 2 FPS).

**\- that's only half of the story -**

Apparently, when I added the details for the upper half of the map image (It originally only had a couple of lines on it for testing) it causes a ton of the lag being involved.

---

**So why does it cause so much lag?**

Well, this is the embarrassing part. Because the player will be working on, there will be a lot of jumping involved. Because of this, I have to pan the *'camera'* while he moves vertically. So, instead of the character moving, everything else actually moves. (All of the trusses, monsters, etc. move instead of the character). So basically, the character is locked vertically (he can move freely horizontally, however). The monsters cause a bit of lag but really, not anything noticeable unless both issues are combined.

Basically, the level is loaded into a multidimensional array. Then, whenever any vertical change occurs to the player (gravity or jumping), an offset equivalent to the amount I want it to appear that he is jumping is applied to **EVERYTHING** (this includes monsters and every block).

The game is made out of 64x64 sprites so there are a total of 10 ladder sprites visible in the screenshot above being moved every time the player moves.

---

**Why I feel dumb...**

First, I recognize the problem: **To many sprites are being moved at the same time**. Second, I recognize the solution: **Only move sprites that are visible or vital (such as monsters)**. The problem is, I'm not sure how to only move the sprites that are visible. I tried dividing everything into vertical chunks of 10 and then check to see which ones are visible and only calculate those but things started getting out of hand! I don't want to ruin the game in the last hours I have working on it!

**Oh, and did I mention? I've wired Lua in, I'm not even compiling the actual code! I'm scripting almost EVERYTHING!**

So, it is my plea to you this day (the very last day of the year no less)! To help me find a quick (dirty if necessary!) solution to my problem!

If it helps, here is a copy of the `level.lua` file I'm currently dealing with:

```
module(...,package.seeall)

local spriteTable={
{name="Blue Truss",color={r=0,g=148,b=255},position={x=0,y=0}};
{name="Red Truss",color={r=255,g=0,b=55},position={x=1,y=0}};
{name="Ladder",color={r=255,g=106,b=0},position={x=0,y=1}};
{name="Stone",color={r=0,g=0,b=0},position={x=1,y=1}};
{name="MonsterBox",color={r=188,g=75,b=0},position={x=0,y=3}};
}

currentLevel={map=nil,offset=0,toffset=0,cerrain={},spawn={x=14,y=96},character=nil}

local LEVELMAX=10

function getVisibleChunks()
    local visible={}
    Print(#currentLevel.map)
    for _,v in ipairs(currentLevel.map) do
        --CHECK TOP
        local pos=base.HEIGHT-((#currentLevel.map-_*LEVELMAX)+1)*64-currentLevel.toffset
        if pos>0 and pos<base.HEIGHT then
            Print("CHUNK ".._.." IS VISIBLE!")
        end
        --CHECK BOTTOM
        pos=base.HEIGHT-((#currentLevel.map-_*LEVELMAX)+1)*64-currentLevel.toffset+(LEVELMAX*64)
        if pos>0 and pos<base.HEIGHT then
            Print("CHUNK ".._.." IS VISIBLE!")
        end
    end
end

function play(level,callback)
    currentLevel.map=loadLevel(level)
    --getVisibleChunks()
    me:AddSprite("levelback",0,0,base.WIDTH,base.HEIGHT,0,0,base.WIDTH,base.HEIGHT,1)
    for _y=#currentLevel.map,1,-1 do
        local top=currentLevel.map[_y]
        for _x,obj in pairs(top) do
            table.insert(currentLevel.cerrain,me:AddSprite("objects",(_x-1)*64,base.HEIGHT-(#currentLevel.map-_y+1)*64-currentLevel.toffset,64,64,obj.position.x*64,obj.position.y*64,64,64,2))
        end
    end
    collision.loadTops(currentLevel.map)
    ConnectEvent(base,"keydown",function(input)
        character.sendInput({["direction"]=true,["key"]=input})
    end)
    ConnectEvent(base,"keyup",function(input)
        character.sendInput({["direction"]=false,["key"]=input})
    end)
    ConnectEvent(base,"updated",function(t)
        currentLevel.toffset=currentLevel.toffset-currentLevel.offset
        for _,v in ipairs(currentLevel.cerrain) do
            v:SetPosition(v.position.X,v.position.Y+currentLevel.offset)
        end
        currentLevel.offset=0
        character.update(t)
        monsters.update(t)
        debugger.set("OFFSET: "..currentLevel.toffset)
    end)
    currentLevel.character=me:AddSprite("character",currentLevel.spawn.x*64,base.HEIGHT-(100-currentLevel.spawn.y)*64+29,64,99,128,0,64,99,5)
    currentLevel.toffset=0
    currentLevel.offset=0
    character.set(currentLevel.character,currentLevel.character.position.x,currentLevel.character.position.y)
end

function loadLevel(level)
    local imgmap=me:GetBitmapFromFile("maps\\"..level..".png")
    local map={}
    local cCount=0
    for y=0,imgmap.Height-1 do
        if cCount==0 then
            table.insert(map,{})
        end
        cCount=cCount+1
        local xLevel={}
        for x=0,imgmap.Width-1 do
            local fColor=imgmap:GetPixel(x,y)
            local r=fColor.R
            local g=fColor.G
            local b=fColor.B
            for _,v in ipairs(spriteTable) do
                if (r==v.color.r) and (g==v.color.g) and (b==v.color.b) then
                    xLevel[x+1]={name=v.name,position=v.position}
                end
            end
        end
        --if cCount>=LEVELMAX then
        --  cCount=0
        --end
        --map[#map][y+1]=xLevel
        map[y+1]=xLevel
    end
    return map
end

```

---

**Here are my edits:**

So, the camera pan thing worked nearly perfectly! With some final tuneups, I'm not having any FPS drops at all!

Now, however, (as dumb as this sounds) I've got this issue here:

Is there a way to force some of these elements (such as the background image and the debug info) to stay instead of panning along with everything else?

# Answer
> 9 votes
This will be hard to fix in so little time, especially since you're using such a peculiar structure, but well, let's give it a try. I'll post and edit as I notice the most glaring problems.

**Step 1) Proper Camera Panning**

The first thing that jumped out of your post like a madman was the part where you said:

> So, instead of the character moving, everything else actually moves.

This is a complete **NO**! *You don't need to move anything in the world to simulate a camera*. The only thing you need to do is to pass a view matrix containing the camera translation to the SpriteBatch. This is literally, one line of code:

```
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, Matrix.CreateTranslation(-cameraPosition));

```

Just this! Then all you have to do is change the `cameraPosition` value and everything will be panned for you at no performance cost. (By the way, notice the minus sign). Or better yet, since the camera will always be centered on the player:

1. *Unlock that player, lock the scenario*! Let the player be the one that moves around (and in both axes).
2. Instead of using some `cameraPosition` value, just use the `playerPosition` directly, minus half of the screen size just to make it centered (and don't forget to negate at the end too).

**Step 2) Visibility Check**

You don't mention anything about this (unless I missed it) but are you perhaps drawing **all the tiles** at once? If you're doing that, then it's obviously a major source of problems too. Your camera can only see a certain amount of tiles at once, so you only need to draw those tiles.

**Step 3) "Too many monsters"**

Actually, I doubt it. I've managed to draw thousands and thousands of sprites at once, and never did the application grind to 2 FPS. The amount of monsters you have does not seem like much of a problem. But just to be sure and to gain a little bit of performance, make sure you don't draw monsters that are outside of view.

**Step 4) Disable panning on some elements**

> Is there a way to force some of these elements (such as the background image and the debug info) to stay instead of panning along with everything else?

Simple! Just draw those elements in a separate SpriteBatch block without passing the matrix. For instance:

```
spriteBatch.Begin();
// Draw background
spriteBatch.End();

spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, Matrix.CreateTranslation(-cameraPosition));
// Draw world
spriteBatch.End();

spriteBatch.Begin();
// Draw debug info
spriteBatch.End();

```

---
Tags: xna-4.0, lua, lag
---


title: Copying section of map array

text:
# Question
Title: Copying section of map array
I'm experimenting a bit with pathfinding. I'm using Javascript.

I have a map array as follows:

```
mapArray = [
             [0, 0, 0, 1, 1, 0],
             [1, 0, 0, 1, 0, 0],
             [0, 1, 0, 1, 1, 0],
           ];

```

The map is fairly excessive in size and I would like to take out a portion of it to pass to the pathfinding algo. How could I go about doing this? From the above, I could take out a section to leave this for instance:

```
mapArray = [
             [0, 1, 1],
             [0, 1, 0],
             [0, 1, 1],
           ];

```

Which would be copying from 0,2 through to 1,4 (xy).

My first thought was a for loop but it is failing for a reason I don't fully understand. Probably a misunderstanding of inserting into arrays?

```
var pathfindingMapArray = [];

for ( y = startRow; y < endRow; y++ ) {
    for ( x = startColumn; x < endColumn; x++ ) {

        pathfindingMapArray[y][x] = mapArray[y][x];
    }
}

```

The above fails as a TypeError.

# Answer
> 1 votes
I tested this on jsFiddle and it seems to be working:

```
var pathfindingMapArray = [];
for (y = startRow; y < endRow; y++) {
    var row = [];
    for (x = startColumn; x < endColumn; x++) {
        row.push(mapArray[y][x]);
    }
    pathfindingMapArray.push(row);
}

```

---
Tags: javascript, path-finding
---


# Question
Title: Sampling from Normal Map and Diffuse Map in Pixel Shader
I'm having some issue changing a basic lighting shader to take a normal texture and a diffuse texture for a model and then using the normal texture for lighting. The code is very simple and i can't see where i have gone wrong at all, am i not allowed to sample two textures with the same sampler? This is the output i am getting:

Using the two textures:

THe basic shader code is:

```
Texture2D shaderTexture : register(t0);
Texture2D heightNormalTexture : register(t1);

    float4 PS(VOUT pIn) : SV_Target
{
    float4 diffuseColour = shaderTexture.Sample(SampleType, pIn.texCoord);
    float4 normal = heightNormalTexture.Sample(SampleType, pIn.texCoord);

    float3 litColour = float3(0.0f, 0.0f, 0.0f);

    for(int i = 0; i < 3; i++)
    {
        SurfaceInfo sInfo = {pIn.posW, normal.xyz, diffuseColour, pIn.spec};
        [branch] switch(gLight[i].type)
        {
            case 0: //Parallel
            {
                litColour += ParallelLight(sInfo, gLight[i], gEyePosW);//
                break;
            }
            case 1: //Point
            {
                litColour += PointLight(sInfo, gLight[i], gEyePosW);
                break;
            }
            case 2: //Spotlight
            {
                //litColour += SpotLight(sInfo, gLight[i], gEyePosW);
                break;
            }
        }
    }
    return float4(litColour, diffuseColour.a);
}

```

The lighting code seems to work just fine when i pass in the normals as part of the vertex buffer, but goes this odd mash-up of diffuse and normal when i try to use the normals from a texture. From what i can tell i am setting the texture right in C++.

```
    ID3D11ShaderResourceView *pixelShaderTextures[2];
pixelShaderTextures[0] = m_textureManager.GetTextureResourceView(std::string("TestHeightMapNormal"));
pixelShaderTextures[1] = m_textureManager.GetTextureResourceView(std::string("TestTexture"));

context->PSSetShaderResources(0, 2, pixelShaderTextures);

```

If you guys have any help/advice for me to resolve this, that would be great.

# Answer
> 4 votes
I've not touched DX11, but in the shader you seem to expect sampler 0 to be the diffuse, with sampler 1 to be the normal map. When you set the textures on the C++ side, you seem to have the slots reversed from what I can see.

---
Tags: directx, hlsl, fragment-shader, normal-mapping
---


# Question
Title: What should be taken into consideration when choosing a math library for games?
I'm currently selecting a C++ math library to use for a project. There are several questions here and on SO concerning the 'best' library available and many answers with different suggestions, but I would like to run some tests on each of them before I make a decision.

I would like to select a library that will cater for my current needs but also for any needs in any projects I may work on in the future. My problem is that due to being fairly new at this, I'm not entirely sure what those needs will be yet.

Aside from the points that I can think of listed below, and assuming that I will only test libraries with a suitable license, **what other commonly used features should I test/look for before making a selection?**

* Matrix operations - including addition, subtraction, multiplication, inversion, transposition, translation, rotation, scale
* Vector operations - cross/dot product, normalisation, zeroing, magnitude, length2, scalar operands, normal calculation
* Euler angle + Quarternion operations - rotation, interpolation, conversion, inversion, multiplication
* Coordinate system conversion (Cartesian, spherical)
* Random numbers - generator speed, period, statistical randomness
* Possibly noise generation
* Ease of integration with gl functions like glTranslate()

Also, assuming these libraries have been tested for mathematical accuracy, **are there factors other than ease of use (documentation, mailing list/developer access), speed (vectorisation, SIMD), and memory usage to consider?**

# Answer
> 1 votes
Your list of functions looks pretty exhaustive, possibly containing more than you actually need.

Given the number of libs out there, my personal priority list when picking which one to use is:

* license (GPL is out, unless project is GPL to begin with)
* portability
* comfortability of use - this is mostly personal opinion, and cause for the multitude of libs out there
* documentation
* capabilities
* clarity of source code (so when docs run out, you still can figure it out)
* performance

Most of the time, math lib performance isn't your bottleneck. This naturally depends on what you're expecting to do with it.. First make it work, then make it fast. Profile your code. Premature optimization, etc.

Also, if you're integrating some physics package, it's bound to have a math lib integrated. You might want to check it out before adding another one.

# Answer
> 4 votes
This may not be the best answer for this question but during game development you may encounter many more greater challenges than the performance and stability of math library you are using. I'm not a man of c++ but before a math library what you have to decide is

1 ) Your game, your needs

2 ) The most suitable framework for your game or no framework if you want to let you develop it asap. And is consistent at least with its graphics and maths.

The most common mistake around programmers including me is to lost your way around frameworks and libraries and spent great amount of time on what to use instead of real usable code production.

# Answer
> 2 votes
Since you mentioned noise generation and random numbers I'd like to answer with a slight different response: portability.

Most math libraries are going to target specific systems such as little endian win32 platforms. This is fine if you are only planning on meeting those targets but is really going to hold you back if you ever plan on porting to a portable device or - and this is the main reason for my response - **porting your algorithms to shaders.**

Perlin noise is a great example but a random number generator could also be ported as well as vector operations to shader work. GPUs are pretty much designed for bulk vector operations and if you plan on using the result for GPU work you now have the result in GPU memory.

Additionally you should also consider threading whether or not you port to other devices. With threading becoming a larger and more important I highly recommend looking for or designing libraries with support for multithreading. For example if a 4x4 Matrix class can be shared across threads you probably should have some locks around common operations so you don't read it in a half modified state. This really applies to random number generators more than anything though it isn't an issue if you aren't looking for determinism.

# Answer
> 1 votes
The library should not be a problem for your project. If it is your case that means that you are coupling your system with a library: this generally is not good idea. What if another better library emerges? And if the library you choose dies?

Try to stay orthogonal to the implementation of every basic library (unless you are coding a thin wrapper around it) and focus on your needs: this will decrease the amount of work need when/if you will need to change library.

---
Tags: c++, mathematics, software-engineering
---


# Question
Title: How do I respond to keyboard events which occur between polling?
In my games update loop, which happens on a fixed timestep of 30 times per second, I am checking the current state of several keys to determine how to move the player. For example:

```
if(Keyboard.down(KEY_LEFT) { /* move character left */ }

```

This works fine in situations where I expect the player to hold the key down for extended periods (such as movement), but for things like shooting, where the player just taps the key quickly, it doesn't always pick up the key being down.

This is due to the key being both pressed and released in the gap between polling.

Now obviously I don't want to trigger my shooting code 30 times a second like I do my moving code, so the solution needs to incorporate some kind of buffering/delay mechanism to make sure each shot is still x milliseconds apart, but I need the first one to register immediately and with certainty.

I am using Javascript, so I can easily use event driven functions linked to keypresses (in fact I am doing this already in order to keep track of which keys are down), but I didn't want to have game logic outside of the fixed timestep update.

Can anyone suggest a solution? I'm not looking for code, more an idea of how to design/structure the code around the problem.

# Answer
> 4 votes
Use the event driven API already provided for you, but instead of executing the events immediatly, queue and batch them to be executed in the next update iteration.

Here's an example in C# which I suppose you'll be capable of adapting to Javascript. In this case all events will be executed during the next frame after they were created:

```
var keyEventQueue = new List<Pair<object, KeyEventArgs>>();

private void OnKeyPress(object sender, KeyEventArgs e)
{
    keyEventQueue.Add(new Pair(sender, e));
}

public void Update(float elapsed)
{
    foreach(var evt in keyEventQueue)
    {
        // Handle evt
    }
    eventQueue.Clear();
}

```

But if you'd like to ensure that there's at least one frame of delay *between* each event being handled, you simply need to change the Update method to:

```
public void Update(float elapsed)
{
    if(keyEventQueue.Count > 0)
    {
        var evt = keyEventQueue[0];
        // Handle evt
        keyEventQueue.RemoveAt(0);
    }
}

```

# Answer
> 1 votes
That's the reason why APIs usually export things like KeyDown and KeyUp (or KeyPressed / KeyReleased). That way you don't check if a key is currently pressed, but its derivative. You then bind the action "Fire" to "KeyPressed", and the problem doesn't even exist.

# Answer
> 0 votes
What's you problem with having that little firing code not being in you timestep update? I'd model my gamestate object to have a `firePressed` function that I call from the `keyPressed event handler`, that firePressed will create a new bullet or whatever it is and in the game's timesteop update I'd only do stuff like expiring bullets wether the hit something or went outside the viewfield.

# Answer
> 0 votes
to get a pattern like that:

```
if (keyDown[KEYCODE_ENTER]) ...

```

you should attach event handlers for keydown and keyup. the event handlers respectively set/unset a property on an object (`keyDown` in the following example):

```
var keyDown = {};
document.attachEventHandler('keydown', function(event) {
    keyDown[ev.keyCode || ev.which] = true;
}, false);
document.attachEventHandler('keyup', function(event) {
    keyDown[ev.keyCode || ev.which] = false;
}, false);

```

---
Tags: javascript, events, keyboard, polling
---


title: Pokemon Battle System A.I

text:
# Question
Title: Pokemon Battle System A.I
For my newest project, a Pokemon fan-edition, I need to collect much information on the game mechanics. So I need to know a few things about the A.I. implemented in the games. For the sake if simplicity here are my questions:

1. Do today's Pokemon games (Diamond, Pearl, Platinum, HeartGold, SoulSilver, Black, White) include an A.I. or is everything more or less random?
2. Has anyone information or even resources on that topic so that I can reuse this to build my battle system?

# Answer
It's not exactly Pokemon, but I think I've got just the thing for you. There are a couple of Final Fantasy VII FAQs down at GameFAQs that might be useful for understanding how this sort of behavior might work. In particular:

The first one is probably the most interesting for you, because it presents (in pseudocode) the AI for every enemy in the game. For instance, here's part of the AI for one of the enemies (as you can see, it's a mix of scripting with random probabilities):

```
AI: Main
{
   If (Stage == 0) Then
   {
      Choose Random Opponent
      1/4 Chance: Use <Bodyblow> on Target
      3/4 Chance: Nothing
   } Else If (Stage == 1) Then {
      Choose Random Opponent
      1/6 Chance: Use Bubble on Target
      1/6 Chance: Use <Bodyblow> on Target
      1/3 Chance: Nothing
   } Else If (Stage == 2) Then {
      Choose Random Opponent
      1/4 Chance: Use Bubble on Target
      1/4 Chance: Use <Bodyblow> on Target
      1/2 Chance: Nothing
   } Else If (Stage == 3) Then {
      Choose Random Opponent
      1/2 Chance: Use Bubble on Target
      1/2 Chance: Use <Bodyblow> on Target
   } Else {
      Choose Random Opponent
      Use Bubble on Target
      Choose Random Opponent
      Use <Bodyblow> on Target
   }
}

```

The second one is mostly about the formulas used in the game. Damage formulas, elemental weakness formulas, etc, which you might also be interested in. For instance:

```
Base Damage = Att + [(Att + Lvl) / 32] * [(Att * Lvl) / 32]
Damage = [(Power * (512 - Def) * Base Damage) / (16 * 512)]

```

If anything, I think at least these will serve as inspiration.
> 8 votes

---
Tags: ai, game-mechanics, nintendo
---


title: Effective SpriteBatching in XNA?

text:
# Question
Title: Effective SpriteBatching in XNA?
What is an example of efficient sprite batching in XNA?

I don't know when (if ever) I would do something like this:

```
spriteBatch.Begin()
DrawSprite1();
spriteBatch.End();

spriteBatch.Begin();
DrawSprite2();
spriteBatch.End();

```

Is there any time within a draw method that I would separate drawing calls like this?

Thanks!

# Answer
> 4 votes
Effective usage is only using one single `spritebatch` for the game. Simply call `Begin()` at the start of the frame and `End()` at the end.

However, there are some usage for multiple batches. You can set them up only draw the content when you call `End()`. With this you could use one `spritebatch` for the game and one for the GUI with having problem with game elements overlapping GUI elements. Link

---
Tags: xna, 2d, textures, efficiency, spritebatch
---


# Question
Title: How can I achieve a zoom-like camera effect?
I have a top down 3D camera:

```
view = Matrix.CreateLookAt(new Vector3(0,0,20), Vector3.Zero, Vector3.Up);

```

Now I want to achieve the effect like when I zoom in the scene and only show a section at the middle of my actual scene. When I now move an object via `CreateTranslation` it looks more like moving an object in 2D.

What I have now is:

What I want is more like this:

# Answer
> 5 votes
What I think you want is an orthographic projection instead of a perspective one. Matrix.CreateOrthographic is what you should use.

You may have to do some additional rotation on the orthographic matrix to have it look down instead of forwards, but that's as easy as multiplying the view matrix by a 90 degree rotation matrix on the X axis.

---
Tags: xna, 3d, xna-4.0, camera, view
---


# Question
Title: How do I disable texture filtering for sprite scaling in XNA 4.0?
I have a sprite that I'm trying to scale up in XNA, but XNA is applying some sort of texture filtering that smooths it and makes it look ugly. I'd like it to just do pixel doubling instead of interpolation. How would I accomplish that?

# Answer
> 28 votes
You need to set the sampler state. The default for SpriteBatch is `SamplerState.LinearClamp` (ie: linear interpolation - the smooth/blurry one).

Choose one of the `SpriteBatch.Begin` calls that takes a `SamplerState` and pass in `SamplerState.PointClamp` (selects the pixel at that precice "point").

# Answer
> 13 votes
Just in case someone else is wondering how to do this outside of a sprite batch, you would do this just before rendering your primitives:

```
this.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;

```

This has to be done on every frame, if there are other items in your rendering pipeline that would change this value (like a `SpriteBatch`).

---
Tags: xna, c#, xna-4.0, sprites, spritesheet
---


# Question
Title: How do I determine if a tile is a slope based on the tile image?
In my game, every tile is a 32x32 texture. All the slopes are a 0 - 45 degree angle. I would like to determine, at the time I load the tile, if the is sloped by examining its texture/bitmap data. How can I do this?

# Answer
> Every tile is a 32x32 texture. All the slopes are a 0 - 45 degree angle. And yes I'm determining the slope at load time only.

Under this assumption, and that other non-slope tiles won't have strange variations, the simplest solution I can think of is the following.

* If blue pixel is empty and purple pixel is filled, the tile is a right slope.
* If green pixel is filled and yellow pixel is empty, the tile is a left slope.

If you're using alpha transparency on your tiles, you can check if a pixel is empty by seeing if its alpha value is 0.

In pseudocode:

```
s = image size
if(image[0,s-2].alpha == 0 && image[s-1,0].alpha != 0)
{
    // Right Slope
}
else if(image[0,0].alpha != 0 && image[s-1,s-2].alpha == 0)
{
    // Left Slope
}

```

As for getting the color at specific pixel on a texture, check the OpenGL API.
> 1 votes

---
Tags: opengl, java, tiles, geometry, lwjgl
---


# Question
Title: How do you do very simple texturing in OpenGL 3+?
I managed to create a sphere (calculating all the vertices etc etc). Now I want to apply a texture on it. I have no idea how. I googled some "OpenGL 3 texture tutorials" but I can't seem to find anything simple. I am using shaders btw. Is there anywhere a very basic step by step tutorial on how to implement a texture? A texture is just an image that wraps around a shape right? Sounds simple, but from what I have seen on the web it's kinda complicated.

# Answer
There are three main components to basic texturing.

1. The texture object, which represents a chunk of video memory storing the image.
2. Texture coordinates, also known as UVs, which specify how to apply the 2D image to the 3D triangles of a model.
3. The pixel shader has to perform a texture lookup using the texture object and the UV coordinate for that pixel, which returns a color that can be output or used for further shading.

First you need to create a texture object, which is done with `glGenTextures`. Then bind it using `glBindTexture` with `GL_TEXTURE_2D`, and load an image into it using `glTexImage2D`. (Binding the texture object is how you tell `glTexImage2D` where the image should go.) Loading the image file and extracting/decompressing the image data into a raw bitmap format is your responsibility; OpenGL won't handle this for you. There are a variety of texture formats available, but stick with `GL_RGBA8` for now.

Then, you need to provide UVs. These are normally part of the vertex buffer, so you should include a float2 component in your vertex struct for this. The UVs would usually be created by an artist using modeling software, but they can be generated programmatically as well. In any case, getting the right UVs to the right vertices is your responsibility. Assuming you're using vertex arrays / buffers, you'll use `glTexCoordPointer` to tell OpenGL where the UVs are in your buffer.

Finally, in the shader you'll need to declare a `sampler2D` variable, which will refer to the texture object, and you'll also need to add `vec2` parameters to your vertex and pixel shaders with the `TEXCOORD0` semantic, for the UVs. The vertex shader will receive the UVs from the vertex buffer and should pass them through unchanged to the pixel shader. In the pixel shader, you'll call the `texture2D` function, passing the sampler and the UVs. It returns a `vec4` representing the color of the texture at the sampled point.

When you do the draw call on the application side, don't forget to do `glEnable(GL_TEXTURE_2D)` and `glEnableClientState(GL_TEXTURE_COORD_ARRAY)`. You'll also need to bind the texture object you created, and use `glUniform1i` to set the sampler parameter to 0 (meaning texture unit 0; you'd use other numbers if you were using multiple textures at the same time, such as a color map and normal map).

I assume you can google the GL calls I mentioned to find out all the details. There are a bunch of moving pieces here but really it's not that complicated. Most of the work is just getting your data to the right place at the right time.
> 6 votes

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


title: Good game design books?

text:
# Question
Title: Good game design books?
I have some experience in creating, however I like to have some well written reference material to help me produce better products. Are there any game design books that are not aimed at a particular programming language?

# Answer
> 46 votes
Here's Top 3 books on game design that I'd recommend:

Now, probably the most important thing is that game design as a discipline is pretty thin, but it draws a lot from other areas like art, history, economics, math (specifically theory of probabilities & statistics), psychology, writing and even music & filmmaking. So good books in all those disciplines probably would be equally important for a game designer as well as specific game design books.

# Answer
> 19 votes
I pretty much have Theory of Fun by my side all the time.

# Answer
> 14 votes
I'm sorry if this would sound like a shameless plug, but I developed a visualization service that crawls Amazon data and shows relationships between books. I specifically created visualization for your question and it had all books from Alex Koloskov's answer. I wanted to share those that I couldn't find among answers here but presented in my visualization.

Reality is Broken written by game designer Jane McGonigal it reveals how we can harness the power of games to solve real-world problems and boost global happiness.

The Ultimate History of Video Games Steven L. Kent writes about about games that changed the world, the visionaries who made them, and the fanatics who played them.

The Ultimate Guide to Video Game Writing and Design This one comes from the co-authors of The Chronicles of Riddick game. I haven't read it, but overall reviews are positive.

Among all I really enjoyed reading "The Art of Game Design: A book of lenses" suggested by Alex.

PS: Visualization itself:

# Answer
> 7 votes
Not specific to game design, but The Design of Everyday Things is a good book to get you thinking about user interactions in general.

# Answer
> 5 votes
I can't believe nobody mentioned Game Programming Gems yet. I always considered it to be the standard when it comes to game design.

# Answer
> 4 votes
Game Coding Complete is the best game design book I have. Although it does use C++ for it's examples there are not many. It talks much more about the how to go about doing things, which can be applied to any language. It's also great value (800+ pages I think).

# Answer
> 4 votes
I was very fond of Andrew Rollings and Ernest Adams on Game Design. It goes into depths of interactive game mechanics as related to player, which is the only unique element to game development as editing is to movies.

Having said that I'd consider suggesting screenplay writing material as it shows you what connects with people and what doesn't. I'm not talking about linear progress material here like stories, but what kind of characters connect with people, themes, motifs etc. In that area I suggest these:

If you're really interested in technical aspects of screenwriting you can also take a look at Screenwriter's Bible \- but that one is more oriented towards technical aspects of screenplay formats and structures.

# Answer
> 4 votes
Gamefeel by Steve Swink completely changed they way I think about developing games.

# Answer
> 4 votes
Game design and development are different (often confused) topics. Game design concerns the design of gameplay and game mechanics (rules of the game, so to speak) rather than the actual coding, audio and graphic design involved in implementing the game. I believe this question is about Game design.

* The Art of Game Design: A book of lenses This book is hands-down the best I've come across.
* "Game Design: Theory and Practice" is quite interesting, especially numerous lengthy interviews with prominent game designers.
* "Art of Computer Game Design" stood for two decades as the authoritative book on this topic. Although a bit dated, it still contains much relevant wisdom. It can be legally downloaded free (google for it - I don't have the requisite karma to post a link).
* "Rules of Play" is often cited as a foundational book, but I didn't find it that helpful.

I've also checked out a number of other game design books that didn't do much for me, such as "Fundamentals of Game Design." Many repeat the same few truisms and have a very low signal/noise ratio.

# Answer
> 3 votes
If you want to design a good game you may want to look at resources that have nothing to do with programming, but focus on the ideas behind your game idea.

Such as war gaming, a classic book on War Games is "The Complete Wargames Handbook". The only version I have read is the 1st edition, but it has had 3 edition total. Any edition will be useful and I have enjoyed the book.

The Author, James F Dunnigan, is a long-time war game designer, actually almost a legend in the number of War games he has designed. He writes outside of games on the theory of War also. So if you game is a War game you would get a lot traction by getting at least one of James' books.

The later editions of this book do deal with how Computers can and are used with this type of game.

# Answer
> 2 votes
Rules of Play, Roger Caillois' "Man, Play & Games" and Huizinga's "Homo Ludens" - and of course Koster's "Theory of Fun" as an ANTI-guide (look at the farce that was SWG to understand why.

# Answer
> 1 votes
Don't think I saw this one mentioned, but I couldn't live without "Game Engine Architecture" by Jason Gregory.

http://www.amazon.com/Game-Engine-Architecture-Jason-Gregory/dp/1568814135

# Answer
> 1 votes
http://www.amazon.ca/David-Perry-Game-Design-Brainstorming/dp/1584506687

# Answer
> 1 votes
Real-time Rendering 3rd ed. is a really good book for game rendering, it introduces all the aspects of Computer Graphics and it has abundant resources which lead you to specific field.

# Answer
> 1 votes
All of the best books have already been posted, but there’s one book that I feel is invaluable to a game designer. Your own journal. When you play games, keep a journal nearby and jot down notes. What about the game design did you like? Didn’t like? Did anything really stand out and if so why? Did you disagree with a particular design choice?

You basically just want to write down everything and anything that comes to mind about the design of the game as you play. Having a journal like this will be invaluable to you when you design your own games.

# Answer
> 0 votes
I've really enjoyed reading Level Up - The Guide to Great Video Game Design It's pretty comprehensive about the entire spectrum of game design.

Written by the game designer behind the Maximo series of games it's illustrated in an approachable style. Well worth a read.

---
Tags: game-design, books
---


title: Cocos2 code structure question

text:
# Question
Title: Cocos2 code structure question
I am doing tutorials to learn Cocos2d and have a question. here is the .m code:

```
#import "SceneManager.h"

@interface SceneManager ()
   +(void) go: (CCLayer *) layer;
   +(CCScene *) wrap: (CCLayer *) layer;
@end

@implementation SceneManager

    +(void) goPlay {
        CCLayer *layer = [PlayLayer node];
        [SceneManager go: layer];
}

+(void) go: (CCLayer *) layer {
    CCDirector *director = [CCDirector sharedDirector];
    CCScene *newScene = [SceneManager wrap:layer];

//    Class transition = nextTransition();

    if ([director runningScene]) {
         [director replaceScene:newScene];
}else {
    [director runWithScene:newScene];
}
}

+(CCScene *)wrap: (CCLayer *) layer {
    CCScene *newScene = [CCScene node];
    [newScene addChild: layer];
    return newScene;
}

@end

```

My question is why is there an @interface placed in the .m file and not included in the .h file?

# Answer
> 2 votes
That `@interface Class ()` placed in the implementation file is a class extension to the SceneManager class which defines its **private interface**.

It's being used because `go` and `wrap` are only used by the implementation of this class and nowhere else (i.e. it's a private interface).

The `@private` modifier only works on variables, not on methods, so this is the way to *hide* them.

(Source: stackoverflow)

---
Tags: cocos2d-iphone
---


title: How do I make light objects in XNA?

text:
# Question
Title: How do I make light objects in XNA?
Here's my dilemma : I want to have light sources placeable by the player, in terms of lanterns.

I know the best way to do this is to use pixel shaders, which I have done a lot of research and use on, but it seems so far that the lights are static.

So what would be the best method to create a dynamically lit scene?

I already have to workings of a few classes to make 2d lights (Color, Position, Type, Direction, Power) but it is just rendering that is the problem.

Thanks for your considerations!

# Answer
You should look into Deferred Shading which is great for rendering scenes with a large amount of dynamic lights (video).

As for how to implement it, I recommend starting from here (courtesy of Catalin Zima and Roy Triesscheijn).
> 2 votes

---
Tags: xna, 2d, graphics, rendering, lighting
---