# Question
Title: Why do 3d model drawn to a RenderTarget appear distorted compared to those drawn directly?
I've got a problem drawing a 3D model to a `RenderTarget2D` in XNA 4. When the model is drawn to a render target, and then the render target is later drawn to the screen it appears distorted. (See right image below)

However, if I draw directly to the backbuffer, then everything appears correctly (See left image)

I'm resetting all the states before doing the 3D drawing. (BlendState, DepthStencilState, SamplerStates and RasterizerState)

This is my draw method. I first draw to the render target. Then I use a spritebatch to draw this to the screen (offset to the right for this example). Finally yfor direct comparison I reset the states again and draw the 3d model a second time directly to the back buffer (using the exact same `DrawModel()` method) and it works fine.

```
    protected override void Draw(GameTime gameTime)
    {
        // First set to use a render target.
        GraphicsDevice.SetRenderTarget(_playerBufferRenderTarget);
        GraphicsDevice.Clear(Color.Black);

        // Reset all the states as appropriate for 3d drawing.
        GraphicsDevice.BlendState = BlendState.Opaque;
        GraphicsDevice.DepthStencilState = DepthStencilState.Default;
        GraphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;
        GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;

        // Draw the model (to the rendertarget)
        DrawModel();

        // Go back to the backbuffer.
        GraphicsDevice.SetRenderTarget(null);
        GraphicsDevice.Clear(Color.Black);

        // Now draw the rendertarget to the screen as a sprite (Offset to the right).
// (This looks wrong)
        spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, null, null, null);
        spriteBatch.Draw(_playerBufferRenderTarget, new Vector2(300, 0), null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
        spriteBatch.End();

        // Again, reset the states.
        GraphicsDevice.BlendState = BlendState.Opaque;
        GraphicsDevice.DepthStencilState = DepthStencilState.Default;
        GraphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;
        GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;

        // Now draw the model again, but this time directly to the back buffer.
// (This works).
        DrawModel();

        base.Draw(gameTime);
    }

```

I create the `RenderTarger2D` within the `LoadContent()` method.

```
_playerBufferRenderTarget = new RenderTarget2D(this.GraphicsDevice, 800, 500);

```

This is the DrawModel method for reference although this is basically copied directly from an MSDN sample:

```
    private void DrawModel()
    {
        Matrix[] transforms = new Matrix[_playerModel.Bones.Count];
        _playerModel.CopyAbsoluteBoneTransformsTo(transforms);

        foreach (ModelMesh mesh in _playerModel.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();
                effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateRotationY(modelRotation) * Matrix.CreateTranslation(modelPosition);
                effect.View = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
                effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(90.0f), aspectRatio, 1.0f, 10000.0f);
            }

            mesh.Draw();
        }
    }

```

I've included a link to the Player.fbx model file. Is it possible that this could be caused by something I've done wrong when creating the model.

# Answer
Looks like overdraw due to the lack of depth buffer.

You can specify the depth buffer when you create the RenderTarget2D:

```
 = new RenderTarget2D(this.GraphicsDevice, 800, 500, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8);

```
> 4 votes

---
Tags: xna, rendering, spritebatch
---


title: Can't get debug spew for Direct3D9

text:
# Question
Title: Can't get debug spew for Direct3D9
The Direct3D9 debug runtime's debug output does not appear to be working correctly. I linked against `d3dx9d.lib` instead of `d3dx9.lib` and defined `D3D_DEBUG_INFO` and I also set the debug runtime on in the Direct3D control panel. However, there is still no D3D debug spew in the Visual Studio Output window. Any suggestions as to what I'm missing?

# Answer
> 3 votes
You did everything correctly, however you must run in "Debug" mode - ie press regular F5, not CTRL+F5. *Do not* choose "start without debugging" from Visual Studio.

## Edit

I don't actually use #define `D3D_DEBUG_INFO`, but according to this post you should #define that *before* including the d3d9 headers.

Also be sure you have set to use the Debug version of D3D9 in the DirectX properties window

The debug information will appear in the Visual Studio **Output Window**, not in your console window (if you have created one).

You can also view it using a tool like DebugView

# Answer
> 2 votes
Is it a 64-bit application? I seem to recall there's a separate control panel for x86 and x64 applications in DirectX. It's been a long time since I messed with this stuff but you should be able to see it under the DirectX SDK menu options off the Start Menu, under DirectX utilities (should be one for 32 and 64 bit)

---
Tags: directx9, debugging
---


# Question
Title: C++ and SDL resource management for 2D game
My first question is about stateManagers. I do not use the singleton pattern (read many random posts with various reasons not to use it), I have gameStateManager which runs the pointer cCurrentGameState-\>render(), etc. I want to make a transitioning game, this engine should ideally cover both a platformer and a bird's eye RPG (with some recoding, I just mean the base engine), both of which will load different levels and events, such as world map, dungeon, shops, etc. So I then thought, rather then having to store all this data within all the states, I would break the engine into gameStates, and playStates... when gameState reaches gameStatePlay(), gameStatePlay simply runs the usual handleInput, logic, and render for the playStates, just as the low level gameStateManager does. This lets me store all the player data within the base playstate class without storing useless data in the gameStates. Now I have added a seperate mapEditor, which uses editorStates from gameStateEditor. Is this too much usage of the gameState concept? It seems to work pretty well for me, so I was wondering if I am too far off a common implementation of this.

My second question is on image resources. I have my sprite class with nothing but static members, mainly loadImage, applySurface, and my screen pointer. I also have a map pairing imageName enums with actual SDL\_Surface pointers, and one pairing clipNumber enums with a wrapper class for a vector of clips, so that each reference in the map can have different amounts of clips with different sizes. I thought it would be better to store all these images, and screen within one static body, since 20 different goblins all use the same sprite sheet, and all need to print to the same screen, and of course, this way I do not need to pass my screen reference to every little entity. The imageMap seems to work very well, I can even add the ability to search through the map at creation of entity type to see if a particular image at creation, creating if it doesnt exist, and destroying the image if the last entity that needs it was just destroyed. The vectored clip map however, seems to take too long to initialize, so if i run past the state that initializes them to fast, the game crashes \>\<. Plus, the clip map call is half of this line =P

```
SPRITE::applySurface( cEditorMap.cTiles[x][y].iX,
    cEditorMap.cTiles[x][y].iY,
    SPRITE::mImages[ IMAGE_TILEMAP ],
    SPRITE::screen,
    SPRITE::mImageClips[IMAGE_TILEMAP]->clips.at( cEditorMap.cTiles[x][y].iTileType ) );

```

Again, do I have the right idea? I like the imageMap, but am I better off with each entity storing its own clips?

My last question is about collision detection. I only grasp the basics, will look at per-pixel and circular soon, but how can I determine which side the collision comes from with just the basic square collision detection, I tried breaking each entity into 4 collision zones, but that just gave me problems with walking through walls and the like \>\<. Also, is per-pixel color collision a good way to decide what collision just occured, or is checking multiple colors for multiple entities too taxing each cycle?

# Answer
The simplest State Manager system I can think of doesn't use a stack or multi-object structure whatsoever, or even a "StateManager" type of object. You just need a GameState class with an Update function that returns a GameState pointer.

When its main function begins to run, assign a pointer, say, called "currentState", to a new GameState you want to run on startup.

In the game's main loop declare another GameState pointer called "nextState" and assign it to currentState-\>Update(). Depending on input and other events happening in the Update function, the function can either return the GameState it belongs to (continuing as normal), or a different GameState (something happened in the game requiring to switch modes).

After this update, compare nextState to currentState. If they are not equal, delete currentState and then assign it to nextState.

This is good enough for basic games which do not care in what order states have entered/left. It's a little tougher for a beginner to wrap their head around, but the code is much lighter.
> 1 votes

# Answer
*Is this too much usage of the gameState concept?*

It's hard for me to answer based on your description, but it sounds like a reasonable use of the state pattern. The game transitions between states to handle input and rendering differently, but the game engine (the means of handling input and ui, etc) remains the same. Just be sure you're not using the state pattern strictly to simplify your class hierarchy, which you mentioned briefly. There are better ways to handle that.

I recommend following Gajet's advice and breaking out the second and third questions into their own posts.

Good luck.
> 0 votes

---
Tags: c++, sdl, resource-management
---


# Question
Title: How does Terrain following work on height map?
I'm writing a 3D world game which consists of a terrain map (generated by brownian motion algorithm) and a simple avatar. My goal is to make the avatar move smoothly between points of different height. Originally, I simply translate from start location to stop location, then set the height of this point based on the height value of a pair (x, z). Unfortunately the movement is completely off. I searched online I found several algorithms to create a smooth movement but I was not able to put them together. I just started to lean graphics for a month, so sorry for my dull knowledge.

My height map size is 512 * 512, and the spacing between each vertex is 150. Base on these values, I create a square around my destination as follows:

```
/*
                        * A            B
                        * --------------
                        * |            |
                        * |    x       |
                        * |            |
                        * |            |
                        * --------------
                        * C            D
                        */

                // build square ABCD around stopLocation
                int x = (int)stopLocation.X / 150;
                int z = (int)stopLocation.Z / 150;

                Vector3 A = new Vector3(x * 150, stage.surfaceHeight(x * 150, z * 150), z * 150);
                Vector3 B = new Vector3((x + 1) * 150, stage.surfaceHeight((x + 1) * 150, z * 150), z * 150);
                Vector3 C = new Vector3(x * 150, stage.surfaceHeight(x * 150, (z + 1) * 150), (z + 1) * 150);
                Vector3 D = new Vector3((x + 1) * 150, stage.surfaceHeight((x + 1) * 150, (z + 1) * 150), (z + 1) * 150);

```

I use a simple algorithm to determine my destination plane:

```
public bool isInUpperPlane(Vector3 A, Vector3 B, Vector3 C, Vector3 D, Vector3 point) {

            /*
                   ^ y
                   |
                   |
                   |
                   |  A       B
                   ----------------------------> x
                  /          /
                 /      x   /
              C /_________ / D
               /
              /
             /
            v z
            */

            // consider A as the origin
            if (Math.Abs(point.X - A.X) + Math.Abs(point.Z - A.Z) >= 150)
                return true;
            return false;
        }

```

Next I construct a plane the 3 vertices (either ABC or BCD):

```
     Plane destPlane;
     if (isInUpperPlane(A, B, C, D, stopLocation)) {
         destPlane = new Plane(A, B, C);
     }
     else {
         destPlane = new Plane(B, C, D);
     }

```

Then I project this my start location to this plane normal, and translate my avatar to this location:

```
Vector3 normal = destPlane.Normal;
Vector3 r = projectVectorToPlane(startLocation, normal);
Orientation *= Matrix.CreateTranslation(startLocation);

```

But doing this make my avatar stays still. It's very very wrong, but I really don't know how it actually works. The 3D world is just too confusing at this moment. Could anyone help me explain what's go wrong? An minimal working example would be greatly appreciated.

This is my original implementation, (not smooth following)

```
public void updateMovableObject() {
            Vector3 startLocation = Translation;
            Vector3 stopLocation = Translation;

            Orientation *= Matrix.CreateTranslation(-1 * Translation);        // move to origin
            Orientation *= Matrix.CreateRotationY(yaw);                       // rotate
            Orientation *= Matrix.CreateRotationX(pitch);
            Orientation *= Matrix.CreateRotationZ(roll);

            stopLocation += ((step * stepSize) * Forward);                    // move forward

            // if collision, reset location and return
            if (model.IsCollidable && collision(stopLocation)) {
                Orientation *= Matrix.CreateTranslation(startLocation);        // don't move
                return;
            }

            // no collision test if move on terrain
            if (stage.withinRange(this.Name, stopLocation)) {
                Orientation *= Matrix.CreateTranslation(stopLocation);         // move forward
            }
            else { // off terrain, reset location
                Orientation *= Matrix.CreateTranslation(startLocation);        // don't move
            }
        }
        stage.setSurfaceHeight(this);

 public void setSurfaceHeight(Object3D anObject3D) {
            float terrainHeight = terrain.surfaceHeight((int)(anObject3D.Translation.X / spacing), (int)(anObject3D.Translation.Z / spacing));
            anObject3D.Translation = new Vector3(anObject3D.Translation.X, terrainHeight, anObject3D.Translation.Z);
        }

```

**EDIT**

```
 public float surfaceHeight(int x, int z) {
            if (x < 0 || x > 511 || z < 0 || z > 511)
                return 0.0f;  // index valid ?
            return (float)terrainHeight[x, z];
        }

```

# Answer
What you have seems like a lot of work to put your avatar on the terrain at a given point. Here's the method I use to calculate terrain height. Simply pass in your X and Z coordinates and it will return the terrain height. In this case, the `scaleFactor` you pass in should be 150. Given something like this you just pick two pairs of X,Z coordinates, get the terrain height at each, and set these points as your start and end points, and then call this method each frame to make sure the avatar stays on (or at least above) the terrain.

```
/// <summary>
/// Get the height of the terrain at given horizontal coordinates.
/// </summary>
/// <param name="xPos">X coordinate</param>
/// <param name="zPos">Z coordinate</param>
/// <returns>Height at given coordinates</returns>
public float GetTerrainHeight(float xPos, float zPos, float scaleFactor)
{
    // we first get the height of four points of the quad underneath the point
    // Check to make sure this point is not off the map at all
    int x = (int)(xPos / scaleFactor);
    int z = (int)(zPos / scaleFactor);

    int xPlusOne = x + 1;
    int zPlusOne = z + 1;

    float triZ0 = (this.heightData[x, z]);
    float triZ1 = (this.heightData[xPlusOne, z]);
    float triZ2 = (this.heightData[x, zPlusOne]);
    float triZ3 = (this.heightData[xPlusOne, zPlusOne]);

    float height = 0.0f;
    float sqX = (xPos / scaleFactor) - x;
    float sqZ = (zPos / scaleFactor) - z;
    if ((sqX + sqZ) < 1)
    {
        height = triZ0;
        height += (triZ1 - triZ0) * sqX;
        height += (triZ2 - triZ0) * sqZ;
    }
    else
    {
        height = triZ3;
        height += (triZ1 - triZ3) * (1.0f - sqZ);
        height += (triZ2 - triZ3) * (1.0f - sqX);
    }
    return height;
}

```

**EDIT:**

Here's the code to calculate the surface normal at any point on the terrain.

```
/// <summary>
/// Setup <see cref="Terrain"/> normals. Normals are used for lighting, normal mapping, and physics with terrain.
/// </summary>
private void SetupTerrainNormals(float scaleFactor)
{
    VertexTerrain[] terrainVertices = new VertexTerrain[this.size * this.size];
    this.normals = new Vector3[this.size, this.size];

    // Determine vertex positions so we can figure out normals in section below.
    for(int x = 0; x < this.size; ++x)
        for(int z = 0; z < this.size; ++z)
        {
            terrainVertices[x + z * this.size].Position = new Vector3(x * scaleFactor, this.heightData[x, z], z * scaleFactor);
        }

    // Setup normals for lighting and physics (Credit: Riemer's method)
    int sizeMinusOne = this.size - 1;
    for (int x = 1; x < sizeMinusOne; ++x)
        for (int z = 1; z < sizeMinusOne; ++z)
        {
            int ZTimesSize = (z * this.size);
            Vector3 normX = new Vector3((terrainVertices[x - 1 + ZTimesSize].Position.Y - terrainVertices[x + 1 + ZTimesSize].Position.Y) / 2, 1, 0);
            Vector3 normZ = new Vector3(0, 1, (terrainVertices[x + (z - 1) * this.size].Position.Y - terrainVertices[x + (z + 1) * this.size].Position.Y) / 2);

            // We inline the normalize method here since it is used alot, this is faster than calling Vector3.Normalize()
            Vector3 normal = normX + normZ;
            float length = (float)Math.Sqrt( (float)((normal.X * normal.X) + (normal.Y * normal.Y) + (normal.Z * normal.Z)) );
            float num = 1f / length;
            normal.X *= num;
            normal.Y *= num;
            normal.Z *= num;

            this.normals[x, z] = terrainVertices[x + ZTimesSize].Normal = normal;    // Stored for use in physics and for the
                                                                                // quad-tree component to reference.
        }
}

```

And here's the code to retrieve the normal at any point.

```
/// <summary>
/// Gets the normal of a position on the heightmap.
/// </summary>
/// <param name="xPos">X position on the map</param>
/// <param name="zPos">Z position on the map</param>
/// <returns>Normal vector of this spot on the terrain</returns>
public Vector3 GetNormal(float xPos, float zPos, float scaleFactor)
{
    int x = (int)(xPos / scaleFactor);
    int z = (int)(zPos / scaleFactor);

    int xPlusOne = x + 1;
    int zPlusOne = z + 1;

    Vector3 triZ0 = (this.normals[x, z]);
    Vector3 triZ1 = (this.normals[xPlusOne, z]);
    Vector3 triZ2 = (this.normals[x, zPlusOne]);
    Vector3 triZ3 = (this.normals[xPlusOne, zPlusOne]);

    Vector3 avgNormal;
    float sqX = (xPos / scaleFactor) - x;
    float sqZ = (zPos / scaleFactor) - z;
    if ((sqX + sqZ) < 1)
    {
        avgNormal = triZ0;
        avgNormal += (triZ1 - triZ0) * sqX;
        avgNormal += (triZ2 - triZ0) * sqZ;
    }
    else
    {
        avgNormal = triZ3;
        avgNormal += (triZ1 - triZ3) * (1.0f - sqZ);
        avgNormal += (triZ2 - triZ3) * (1.0f - sqX);
    }
    return avgNormal;
}

```
> 4 votes

---
Tags: algorithm, xna-4.0, terrain, heightmap
---


title: Drawing beam effect in UDK?

text:
# Question
Title: Drawing beam effect in UDK?
I'm having trouble drawing a particle effect between two actors in UDK - Both the source and the target are not static objects, so as far as I can tell I need to do it in the code not in kismet. Here's what I've got at the moment and it seems to not be doing anything at all. Ideas?

```
BeamEmitter[0] = new(self) class'UTParticleSystemComponent';
BeamEmitter[0].SetAbsolute(false, false, false);
BeamEmitter[0].SetTemplate(BeamTemplate[0]);

BeamEmitter[0].SetTickGroup(TG_PostUpdateWork);
BeamEmitter[0].bUpdateComponentInTick = true;
self.AttachComponent(BeamEmitter[0]);
BeamEmitter[0].SetBeamEndPoint(2, tarPos);
BeamEmitter[0].ActivateSystem();

```

# Answer
> 1 votes
I dont know if I get your question correctly or not but may be you will find some useful information in these 2 links of udn for showing light beams.

http://udn.epicgames.com/Three/VolumetricLightingGuide.html

http://udn.epicgames.com/Three/FogVolumes.html

Also you can find this article useful for "UDK Dynamic Lighting and Particle Effects"

http://www.lee-3d.com/?p=206

---
Tags: udk, particles
---


# Question
Title: client - server position syncronization in flash
I trying implement client - server position syncronization. Every 20 game ticks i sending to flash client correction of player position... and it always wrong on client, flash always cant predict player position. I think it due to different frame rate or different time on server and client (server is running on 30 fps when client on 60 fps).

Take a look here. How can I implement so precise player movements like they did? Any suggestions?

# Answer
> 2 votes
This document explains what you need to know.

---
Tags: flash, networking, server, client
---


title: Objective-C or javascript+html5+canvas?

text:
# Question
Title: Objective-C or javascript+html5+canvas?
I'm really interested in starting to study some language with the idea of develop games for ipad and iphone.

My main concern is that as soon as is possible to develop games with javascrit and html5 with canvas seems so powerfull, shouldn't be better to invest time in studying javascript+HTML5+canvas instead of Objective-c and the necessary libraries?

Thank you

# Answer
> 2 votes
HTML5 is becoming so powerful that it is very much possible to develop games for mobile platforms using them. If you are planning for simple 2D games, then I would say you go for HTML5.

But if you want to do some big complex games supporting device orientation and other such features, then I suggest you learn Objective-C. Because as of now, there in no direct procedure to make the game stick to one orientation (which I suppose is one of the basic feature). As far as I searched it is not possible to tell the browser to stop auto-rotating on change of orientation.

Another things is about performance. The performance of canvas API inside the browser is good enough for simple games, but it cant compete with the power of native games.

Regarding libraries, on native side there is cocos2d and many other mature libraries; but on HTML5 side I dont think the libraries are not mature enough when compared to native libraries. But soon this problem will vanish as the libraries evolve.

# Answer
> 0 votes
Objective-C and HTML5/JavaScript are quite different. If you have a background in web-technologies, the HTML5 route might be easier for you. If you have some Java or C/C++ experience, you might feel more comfortable with Objective-C.

While it's certainly possible to develop games in both "environments", you shouldn't forget about monetization. You can put your Objective-C app in the AppStore and sell it, while you'll have to find other ways to make money from your HTML5 app (maybe ads or some sort of subscription model?). If your focus is iPad/iPhone, then Objective-C is going to be less of a pain and also give you the better performance.

# Answer
> 0 votes
If your really interested in iOS Development, I STRONGLY recommend you at least learn the fundamentals of Objective C 2.0 and Cocoa Touch.
I'm have quite a bit of experience with iOS development as I'm in a group called theCodeCadets.

---
Tags: javascript, objective-c
---


title: Spritegroups and colorkeys

text:
# Question
Title: Spritegroups and colorkeys
I have a problem using spritegroups in pygame. In my situation I have 2 spritegroups, one for humans, one for "infected". A human is represented by a blue circle:

```
image = pygame.Surface((32,32))
image.fill((255,255,255))
pygame.draw.circle(image,(0,0,255),(16,16),16)
image = image.convert()
image.set_colorkey((255,255,255))

```

An infected by a red one (same code, different color).

I update my spritegroups as follows:

```
 self.humans.clear(self.screen, self.bg)
 self.humans.update(time_passed)
 self.humans.draw(self.screen)

 self.infected.clear(self.screen, self.bg)
 self.infected.update(time_passed)
 self.infected.draw(self.screen)

```

Self.bg is defined:

```
self.bg = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
self.bg.fill((255,255,255))
self.bg.convert()

```

This all works, except that when a red circle overlaps with a blue one, you can see the white corners of the bounding box around the actual circle. Within a spritegroup it works, using the set\_colorkey function. This does not happen with overlapping blue circles or overlapping red circles.

I tried adding a colorkey to self.bg but that did not work. Same for adding a colorkey to self.screen.

# Answer
This is not the problem with colorkey. When you clear the sprites from the second group, you erase parts of the sprites from the first group that were already drawn. To fix it, change the order of clearing and drawing:

```
self.infected.clear(self.screen, self.bg)
self.humans.clear(self.screen, self.bg)

self.humans.update(time_passed)
self.humans.draw(self.screen)

self.infected.update(time_passed)
self.infected.draw(self.screen)

```
> 1 votes

# Answer
Im new enough to python so I may be completely wrong but would it work if you put in pygame.display.flip()

Thats what I have in my game after it is drawn and updated on the screen?
> 0 votes

---
Tags: python, pygame
---


title: Pygame circular cropping/masks

text:
# Question
Title: Pygame circular cropping/masks
I have been going through the documentation and the Pygame functions and classes today, but couldn't find a reasonable way to either create a circular crop of an image or how to use a mask to perform this: assume an empty circle with a line width of 50px, with a single key color, that is supposed to be removed from surface A and then replaced with the contents of the same pixels on surface B (perhaps I'm mixing definitions here between Pygame's Mask and image editors' - such as Photoshop - masks).

I know surfarray can be used for the task (after a list of pixel coordinates is extracted from surface B), but my tests were too slow and ended up hanging the main loop.

Is there a way to achieve the described above through an efficient and quick method, that can be embedded into the main loop of the application without a significant drawback to the overall processing?

# Answer
> 1 votes
Generally speaking it isn't possible to do real-time per-pixel masking with software renderers if performance is a concern. So you need to do the processing offline.

I don't understand the task you are describing - masking is merely the act of selecting certain pixels to avoid operating on, so it sounds more like you are using a mask to perform some sort of colour replacement. If not, and you are literally just looking to render a part of surface B over a part of surface A, then the answer is to process surface B before the main loop starts so that the pixels you don't want to render have alpha values of zero.

If you need to recalculate this masked area every frame, then you're pretty much out of luck with PyGame - it uses a software renderer and doesn't provide the type of modern GPU operations that would make this practical on anything but tiny images.

# Answer
> 1 votes
You can do it quite fast with two blits and one copy. If you use colorkey, then:

1. Have your mask image composed of two colors -- one the "transparent" color of all your other images, and some other color.
2. Set colorkey on your mask to that other color.
3. Copy the source image.
4. Blit your mask on that copy.
5. Set colorkey on that copy to your "transparent" color.
6. Blit that copy on your target image.

If you don't use colorkey, you can achieve a similar effect using the alpha channel and the special\_flags of the blit method.

---
Tags: python, pygame, image
---


# Question
Title: Find a line that connects the outer most points in a set of points
Does anyone know an efficient algorithm to find the edge of a point cloud? Hopefully the picture in the link can illustrate what I mean. It's a plus if the algorithm can handle point clouds that are distinctly separated in space. The algorithm only needs to work in 2D.

Many thanks!!

http://uploadpic.org/storage/2011/4n68m1OYLSYIGt8vfuJrK1LnA.png

# Answer
> 7 votes
You want to compute the convex hull of your point data: http://en.wikipedia.org/wiki/Convex\_hull

I'd recommend the qhull software written in C: http://www.qhull.org/

Here is their licensing info: http://www.qhull.org/COPYING.txt

# Answer
> 8 votes
Discounting the fact that your image shows two point clouds not one, I'm going to assume that you don't want to do cluster analysis to find 'blobs' of points. If you do, just do that first.

The primary part of the problem (the boundary polygon) needs more definition. If you just want a convex hull, then the gift-wrapping algorithm works fine. If you want a tighter fit (as shown in your image), then you need to alter the criteria by which points are rejected.

In the basic gift-wrapping algorithm, you start at a point known to be on the boundary (the left-most point), and pick points such that for each new point you pick, every other point in the set is **to the right** of the line formed between the new point and the previous point.

To get a tighter fit, all you need to do is modify the rejection criteria. Instead of rejecting points which have any points 'to the left', you reject points which have others which fall within the area bounded by a line extending out to the left, perpendicular to the boundary line. Hard to describe accurately, so see these examples. The black dotted line denotes the area within which any points would cause the line to be rejected.

So to test a line segment, you iterate the other points in the cloud. Make a line between the test point and the endpoint of the line, and calculate the angle between the boundary line and that new line. If the angle is less than 90 degrees, the point lies in the problem area.

NB: this is the exact same check the standard gift-wrapping algorithm uses, except the usual limit is 180 degrees. As you reduce that angle, more and more points will be allowable, and as you tend to 0 degrees, eventually any point will be valid (and your boundary will look more and more spiky).

It's worth noting that with an angle less than 180, you also have to test all points rather than just dropping out with the first one you find. That's because the standard convex hull finding is looking for a minimal number of points, and either a point is on the convex hull or it isn't. With this modification, there will potentially be multiple points which satisfy the conditions, and so multiple choices for where your boundary line goes next. Which you choose is up to you - the one furthest away will give you a boundary with minimal line segments, and the one closest to you is more likely to give you a tighter fit to the points.

---
Tags: algorithm, point-cloud
---


title: Game Design Education

text:
# Question
Title: Game Design Education
I am very interested in a career as a video game designer. to clarify i mean one of the people to figure out how the mechanics, story, levels and art all work together. To any designers on the website what post-secondary education should I look for? I know that typically they have knowledge of all different parts of game development but is there anything specific I should be looking for that would helpful as a base?

# Answer
> 1 votes
I would say, make yourself useful as something else than game designer. Be it programming, graphics, level design, writing or music. Anything else than game design. Why is that? Cause game design is not entry point to game industry. I think you will have best chance to become game designer from jobs like programmer or artist... or writer if you somehow manage to become game writer (but it's about as hard as becoming game designer). Generally bigger your role on project = better chances that you may become game designer.

# Answer
> 1 votes
Judging based on those who I know in the AAA industry, the most common path to Game Designer, Lead Designer, Director, so on; is via Level Designer. Level design is one of the few entry level positions in the industry that both makes use of varied skills (programming, music, story, graphics) and also showcases them well in terms of Game Design. In a very real sense, level designers are smaller-scale Game Designers.

However, you need to be able able display all of these skills in your application. What I've seen work the best is having a portfolio of examples in the company's own product, or a related one where a mod tool isn't available. For example, if you want to work for Piranha Bytes on the next Gothic, you should submit example levels that show a mastery of all the aspects of the Elder Scrolls Construction Kit. Since Gothic doesn't have any studio provided mod tools.

If you can't swing something like that, you won't be able to get an entry level LD position. In this event your best bet is to get really good at one of the other entry level positions. The more technical the better, but there are examples of Lead Designers who have come up through art, music, and probably even testing.

This all focuses on being the Director/Lead Designer of a game. This is because the goal of basically all Game Designers is to design their own game, not the games of others. There are, however, non-lead Game Design positions. Especially now when every AAA title has mini-games of a million types. Someone needs to design these mini-games and typically that's someone who is either being tried out as a potential Lead Designer one day, or someone who has aspirations to that but is actually a member of another team. (Again, I see Level Designers filling this role the most.)

---

This is all apocryphal. I don't work in the AAA industry and never have. I do have a degree in Game Design, and do know a lot of folks in the industry and related fields. But I can't speak from personal experience. Perhaps someone can come along and edit this answer to include first-hand knowledge if they agree with the underlying premise.

---
Tags: game-design, education
---


# Question
Title: How do I shoot bullets towards the mouse in a top down shooter?
I have a formula for pointing my main character of the game towards the mouse, and it gets the angle he needs to be turned to point towards the mouse. But how do I get the bullets from the gun to use the angle produced and shoot a bullet towards the mouse.

# Answer
All you need to know is the relative angle between the player and the point where you are aiming at. It seems to me that you already have the angle, lets call that angle a.

Now for the bullet to point in the right direction you just rotate the bullet sprite with angle a. Now for the movement/direction. You need to convert the angle to a 2D Vector, you can do that by creating a new Vector with X = cos(a) and Y = sin(a). You now have a (normalized) vector pointing from the player to the target. Now all you need to do now is move the bullet every frame with an equal fraction of the X and Y in the vector.
> 6 votes

# Answer
Vec2 delta = MousePos - ObjPos Float angle = atan2(delta.y, delta.x) Then use cos/sin to make a line if you want
> 2 votes

# Answer
If your character has a forward vector, you can just use that to set the rotation of the bullet vector as well as the velocity (by multiplying forward * speed).
> 1 votes

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


# Question
Title: Practice openGL or learn a specific engine?
> **Possible Duplicate:**
> Should I use Game Engines to learn to make 3D games?

I am a university student. I want to work in the game industry. Now I am thinking about either practicing my openGL skills or learn a complete new game engine during my time in school. I will do this by developing a smartphone game. I am debating over using just openGL or using a game engine. If I learn a game engine, then if the company I want to work for does not use that game engine, then wouldn't it be a waste of time to learn that game engine now instead of solidifying my openGL skills? So, openGL or game engine? Thanks.

# Answer
> 4 votes
Learn OpenGL, you don't have to be a pro, just get the feel of it. Try setting up a scene with rotating triangle, cube, texture it, play with blending, play with perspective and orthographic projections (2d and 3d games), learn about display lists, vertex arrays, VBOs... do some toy projects with it like nehe tutorials, then skip to learning an engine of your choice to be more productive with your own game projects. All engines are just layers on top of OpenGL or DirectX so it's good to know what is under the hood and how it behaves.

# Answer
> 2 votes
What Jimmy said is so true, though with most graphics engines (it's important to distinguish it from a game engine), you'll want to modify some code to suit your game, sometimes you'll have to fix a broken feature. Beside that having knowledge of OpenGL will mean you have understanding of how 3D graphics programming works, which is essential.

At the end of the day, which ever engine you choose, the engine is "just" a library, being able to work with it is important if your company is using it, but, i'd say, it's alot more important to have an understanding of the underlying technology, especially that you can do learn it now, when you have time and no deadlines. Knowledge of OpenGL will let you branch out more easily, while the solutions of one engine designer won't always translate to other engines.

It all depends what you want to be doing, it may be that you just want a finished game you can show somebody. Coding in OpenGL will mean that you won't see a game in a long time, it's important to keep that in mind. It doesn't help, that when you create your own engine, if you want tools for it, you have to code them yourself.

There isn't a definitive answer, i'd say, if you're a beginner or intermediate and you want to learn an engine (or an API) while making your first, or second game, don't dive in to OpenGL, simply because you don't know what's ahead of you, there's ALOT more to a game than just graphics. It's better for your morale if you try to bite what you can chew. Finishing a project is alot more important than a list of features and unfinished code.

# Answer
> 0 votes
You should play around with OpenGL so that you can gain an understanding and appreciation for how graphics are really created on the screen, however if you're engaging in any project which you actually want to release to the public and not go mad, I would recommend finding one of numerous libraries out there that will abstract OpenGL even a little bit for you.

---
Tags: opengl
---


title: Recommended Polling Rate

text:
# Question
Title: Recommended Polling Rate
I'm using the *XInput* API to support gamepads. As *XInput* is not event-driven, but requires polling, my question is, **what is the recommended polling rate *(ms)* for gamepads or specific, the *XBOX 360* controller?**

# Answer
The rule of thumb that I'm aware of is that total input-response latency should be under 150ms in order to appear 'instantaneous' to the user. If your game design is fast-paced or emphasizes timing (e.g. fighting games), you should revise that figure downward.

To obtain your minimum polling rate, subtract any other latency sources (physics updates, rendering, etc.) from your target input latency.

Example: let's say you're targeting max input latency of 100ms, and designing for a minimum framerate of 20Hz. It can take up to 50ms to display effects after detecting events, so you need to poll every 50ms to ensure that the effects of an action are displayed within 100ms.

As a mostly irrelevant side-note: USB 2.0 controllers poll devices at a maximum of 8kHz, so it is utterly pointless to have a polling period smaller than 0.125ms.
> 3 votes

---
Tags: controllers, polling
---


# Question
Title: Real-time UDP multiplayer games: ping measurement?
In real-time multiplayer games that use UDP for the actual game (CS:S, UT, etc.), how is network latency (ping) measured? More specifically, how do you find out how long ago a UDP packet was sent?

Sorry if this is a dumb question, but I'm very new to network programming.

# Answer
Just send some 'ping', write timestamp of that packet/session, wait for 'pong' response and get timestamp 'now' and divide the difference by two.
> 6 votes

---
Tags: networking, multiplayer, udp, latency
---


# Question
Title: Is the way I remove objects causing a memory leak?
The game I'm working on consumes memory, and the memory used in megabytes increases around 2MB every 4 seconds.

It starts at 5MB and grows to hundreds of megabytes in minutes.

I was careful, and have little to no new variable declarations in the main game loop (and the existing ones are integers and floats, not SDL\_Surface's and images).

However, I keep creating new instances of classes, such as bullets and enemies, but I'm also careful with those:

```
/* Is a bullet out of the screen? Remove it from the list! */
for (i = 0; i < bullets.size(); i++) {
  if (!bullets[i].is_on_screen(screen))
    bullets.erase(bullets.begin() + i);
}

```

I remove them from the respective vectors when they are no longer needed, and with enemies too:

```
/* Is the enemy death? Put it out of the array! */
for (i = 0; i < enemies.size(); i++) {
  if (enemies[i].health <= 0) enemies.erase(enemies.begin() + i);
}

```

Also, I create new Enemy(ies) with an image, but I only load the image on the beginning of the game, and then pass a pointer of it to the newly created class, so that it can draw it. I'm not creating hundreds of new images of enemies and bullets, am I?

When I erase the instances from the vectors, am I not fully deleting them from RAM?

# Answer
Your iteration through your objects and removing them is incorrect

```
for (i = 0; i < bullets.size(); i++) {
    if (!bullets[i].is_on_screen(screen))
    bullets.erase(bullets.begin() + i);
}

```

Let's say you have 5 bullets.

* First iteration: Remove bullet at index 0. Now `bullets.size()` is 4
* Second iteration: Remove bullet at index 1. Now `bullets.size()` is 3
* Third iteration: Remove bullet at index 2. Now `bullets.size()` is 2.
* And now there will be no more iterations because `i` is larger than `bullets.size()`. Two of the 5 bullets will not be deleted properly.

Instead, remove them in reverse:

```
for (i = bullets.size() - 1; i >= 0; --i) {
    if (!bullets[i].is_on_screen(screen)) {
        bullets.erase(i);
    }
}

```
* First: Remove bullet at index 4. Now `bullets.size()` is 4. Decrement `i` to 3 at end of loop.
* Second: Remove bullet at index 3. Now `bullets.size()` is 3. Decrement `i` to 2.
* Third: Remove bullet at index 2. Now `bullets.size()` is 2. Decrement `i` to 1.
* Fourth: Remove bullet at index 1. Now `bullets.size()` is 1. Decrement `i` to 0.
* Fifth: Remove bullet at index 0. Now `bullets.size()` is 0. Decrement `i` to -1, which no longer evaluates to true in the for loop's conditional statement.

And we're done, now you can see all 5 bullets were removed. By iterating through the bullets in reverse you're able to alter the contents of the `bullets` container without affecting your loop. Some languages, like C#, will throw an exception when a container is altered while you're looping through from begin to end, for reasons like what you're experiencing here, reversing through the container should almost always be what you want to do when altering the container as you go through it.

There may very well be other leaks in your program as well. As others have mentioned already, a profiler might help you catch these leaks. Also, in every game I've made I always create a display UI that will show me the number of objects I have in certain containers, this way I can see in real-time if the number continues to rise and never go down. For example, if your `is_on_screen` method wasn't working properly, and was considering some bullets to always be on screen, they may never get erased. Having a UI to display the bullet count might help you spot this more quickly and easily.
> 13 votes

# Answer
You probably have a memory leak somewhere. Can't help you with that without thoroughly inspecting your code. Are you sure you are calling the destructors after removing them from the list? C++ doesn't have a garbage collector.

However in general you shouldn't, create, delete and then create lots of small objects. It's expensive and fragments your memory (which can also lead to some increase in memory usage). For objects like bullets you could use a pool. A pool is just a big list of instances of bullets that can be re-used. Instead of constructing a bullet when it's fired, and destructing when it hits something, you grab a bullet from the pool and use it, until it hits something when it is returned from the active actors list back to the pool.

A good article on this is: http://wiki.andengine.org/ObjectPool
> 5 votes

# Answer
In addition to Nic's solution, it is a good idea to add a profiler/Heap checker to your debug build, like Google profiler or Visual Leak Detector, to detected ASAP memory problems.
> 4 votes

# Answer
I found the answer! I had to use SDL\_FreeSurface(); to free my SDL\_Surface's!
> 2 votes

# Answer
use iterators like that

```
for(vector<Object>::iterator it = v.begin(); it != v.end(); /* no ++it! */ ) {
    if(ToBeDeleted(*it))
        it = v.erase(it);
    else
        ++it;
}

```
> 2 votes

---
Tags: c++, sdl
---


# Question
Title: Are there games already including detailed psychological/social modeling?
I have this project that have been running in my head for some time, and was surprised to realized I have never seen it in an existing video game. So I thought I might be wrong.

Most of current video games use basic social modeling, for example:

* Actor1 goes from A to B, then back to 1. Repeat
* Actors walk around limited area. When 2 Actors meet, they interact for 10s, then go back to walking
* Actors have complex patterns, e.g. Oblivion (eat lunch under this place at 1am, except if raining, goes to this city on Sundays, etc)

My point is, it is currently mainly based on scripts. To use a graphical equivalent, it is as when physical interactions were limited/scripted, compared to current games having a detailed physics engine allowing realistic and unscripted interactions (think *"Link to the Past"* arrows compared to *"Skyrim"* arrows)

The main difference would be that there are detailed and verified models of physical behavior, gravity, etc, where as psychology/social tend to be more "fuzzy". However, there **are** psychological models out there, some of them widely accepted and verified, and not that difficult to implement (for example, distance between people during a social interaction, group theory, and all that). I believe that it would make a game more realistic, which is often a good point.

An example would be the "pretty rich girl / beggar" situation. In most games, either they interact as soon as they are less than 5ft from each other, and in the same way as two "equal" characters would interact (both are doing gestures while talking, they are talking about the weather, looking each other in the eyes, etc), or they are scripted not to talk to it to each other. In both cases, it would be different than what you would expect in real life.

So, (finally) the question: **Are there games out there that have implemented and modeled real psychological/social models?** Or even tried, and realized it was not working?

# Answer
Generally, very few games use "fuzzy" AI. Most games have AI that is heavily scripted, because if it *isn't* scripted, the AI will do completely crazy, insane things that no human would ever actually do (see: bugs in Oblivion with "Radiant AI"). It's easier to test scripted AI than to try testing fuzzy AI that might not react in any predictable manner.

Even in something like The Sims, the AI is all heavily scripted, with objects broadcasting their locations, and in fact, being the main focus of the AI (the Sims themselves have some level of fuzzy logic AI, but it's all fairly basic). http://aigamedev.com/open/review/the-sims-ai/

That said, there's a few games that stand out for relying less on scripting and more on playing around with unscripted, "fuzzy" AI. One is the Creatures series, where creatures would interact with, and learn about, the world, and the AI was based on neural networks, instead of tons of scripting. The creature in Black and White tended to have an AI built on some basic fuzzy logic stuff, though many players were confused by the whole thing and the creature AI was simplified in the sequel.

In terms of AI in social settings, the one game I know of is Facade, where the AI has a set of script options, but chooses them based on the player input to the conversation. It's halfway between purely scripted, and fuzzy logic AI.
> 5 votes

# Answer
Check "The Sims". If there are games with social interaction implemented, I'm sure this game is among them.
> 2 votes

# Answer
Take a look at Namaste Entertainment's Storybricks project. There is a good writeup on it at http://massively.joystiq.com/2011/08/08/storybricks-opening-the-pandoras-box-of-mmo-design/

They are apparently gearing up for an alpha/beta soon.

Storybooks really lets you specify this kind of emotional and psychological information for an NPC to influence their behavior and how your actions (or those of other NPCs) change how they act.
> 0 votes

---
Tags: game-mechanics, social
---


# Question
Title: What is the best way to implement host-migration application design?
I'm trying to wrap my head around how any one of the clients could become a new host should the current host leave the game. I'm not looking for any code, but more of a high level application design of how a feature like this would work.

# Answer
Leader election is an interesting topic, and there are several solutions available.

One such solution is the "bully algorithm", in which all clients (including the host) have unique IDs, which determine rank/priority to control an election. When a client detects that the host is no longer present, it sends out an inquiry to higher ranked nodes to see if they are active. If it receives no response, it declares itself the leader (host) and notifies all other clients of the change.

You can read more about this method, and a few others, in the Wikipedia article I've linked.
> 3 votes

---
Tags: design-patterns, standards
---


# Question
Title: Managing Shaders and Objects in DirectX 11
The title explains my two biggest logical problems with developing a game. It's something I sit up at night thinking about, and that is "*What is the most effective way to manage shaders*" and "*What is the most effective way to manage objects* (I call them entities in my game)"

Before I actually began to create I game, I made a bunch of simple projects, and my shader and object management systems have always felt flimsy to me. The methods I usually used for shaders were:

1. Preload all the shaders when the game loads
2. All the shaders are based off of "ShaderBase"
3. Each class holds a pointer to a class derived from "ShaderBase"
4. When the object is rendered, the app calls the MapData and Render functions of the ShaderBase derived class that the objects pointer contains

This had some problems, however. First of all, is I usually created a different shader when the entities that use it needed special information (Perhaps it was a water shader, and it would be tessellated, so it needed that information). I would need to map different data types to the shader. That means I'd need different versions of ShaderBase's MapData function, for example a regular entity would use:

```
void ShaderBase::MapData(TransformBuffer transBuf, LightingBuffer lightBuf);

```

but the water would use:

```
void ShaderBase::MapData(TransformBuffer transBuf, LightingBuffer lightBuf, WaterDataBuffer waterBuff);

```

Having to do this seemingly ruins the point of inheritance, because my base class would soon be loaded with different functions for different shaders.

---

Now the methods for object/entity management. I didn't really have any problems, I just felt like maybe there was a better way to do it. Here's this process:

1. Create all the objects (Maybe from a world file)
2. Sort all the objects by purpose and/or shader, to cut down on state changes
3. A class called EntityList would have an array of all the entities, and each frame would run through that array, and call each ones Render() function, and if it is time, a Think() function (Because some entities may think in steps). It also places the object in its rightful location in the world.

I can see how things like instancing can also be applied here to cut down on resource usage. However, I just have a feeling theres a better way to do this. Each entity is derived from EntityBase, so theres no real problems with inheritance. I might be wrong, but I don't want to continue and have to redo this later.

---

I didn't mention this above, but I have a sort of bonus question that came to mind while I was writing this:

With the new DirectX 11 features in shaders, what method is better to use: Using techniques, passes, etc. and effect (.fx) files, or the seemingly newer method (I actually don't know when it came about) with each shader in an individual file (.PS, .VS, etc.). Maybe there isn't a difference, I don't know, but I've seen both used in DirectX 11 applications, and I thought maybe people who were more keen to DirectX 10 would use the effect file method, because when I learned a little DirectX 10 before I moved to DirectX 11, I used that method.

For examples of where I've seen these two methods, I learned most of what I know from these two sites:

http://rastertek.com/tutdx11.html

http://www.braynzarsoft.net/index.php?p=DX11Lessons

# Answer
> 5 votes
I think your overall approach is fine, assuming that everything works. I recommend ignoring your performance concerns until you can show that performance is bad (I got the impression that performance is a personal concern and not yet a technical one).

Your shader base class/interface `MapData` has a problem because it is an abstraction (there is no single way to map data for all shaders), and as such needs an abstract way to receive parameters. Here is one idea to consider:

Use an abstract parameter collection similar to the following:

```
//IShaderParameters.h
class IShaderParameters {
    public:
        virtual ~IShaderParameters();
        TransformBuffer getTransformBuffer() const = 0;
        LightingBuffer getLightingBuffer() const = 0;
}

//ShaderBase.h
//...
class ShaderBase {
//...
virtual void MapData(IShaderParameters* parameters);
//...
}

```

A default shader parameter class would extend `IShaderParameters` for your general purpose shaders. Specialized shaders would receive specialized forms of `IShaderParameters`, like so:

```
//WaterShaderParameters.h
//specialization extends the standard implementation
class WaterShaderParameters : public ShaderParametersBase {
   public:
    //...
    WaterDataBuffer getWaterDataBuffer() const;
    //...
}

```

You'd need to guarantee that the caller knows which shader it's passing parameters to, but this is a problem that you already have.

I hope this helps. Good luck.

---
Tags: architecture, directx11
---


# Question
Title: Using Python what is the best way to perform heavy tasks in the background?
I'm generating large amounts of procedural map data on the fly, however my game engine doesn't rely on them to render the scene and I'd like to build it on in the background and pop it into the world when it's done (as seen in Minecraft).

I've tried using *threadding.Thread* but this seems to interfere with PyGame and the game-loop, even with a low amount of threads.

I'm currently trying to get everything happening using the multiprocessing module - although there's a fair amount of work here, and I don't want to find myself in the same case as with *Thread*.

Is this possible with python? Or should I stop rendering big chunks of data in one go, and rewrite my generation so that it can do lots of smaller jobs spread out over frames in the main thread?

# Answer
One of Python's huge weaknesses is the existence of a global interpreter lock. Essentially all python code is executed while holding this lock. The consequence is that multi-threaded python applications are effectively incapable of parallelism. Threads allow the convenience of a multi-threaded programming model, but multi-threaded python applications will not be able to take advantage of multiple processors.

To my knowledge, there are two ways of attaining parallelism in Python applications:

Probably the 'simplest' is to use multiple processes. (Using the multiprocessing module) Each process has its own address space, and its own global interpreter lock, so they can run in parallel. The downside of this is that inter-process communication is a PITA in general. Probably the easiest is if the process just writes its output to a file, and the 'main' process pulls data from the file after the subprocess has exited. You might communicate over the process's stdin and stdout (requiring marshalling and unmarshalling of text streams, etc.) You could communicate using sockets, which would let you distribute work over a network for free as a bonus, but which would be even more of a PITA than stdin/stdout. The operating system should be able to provide shared memory and shared synchronization primitives, but I'm not sure if any of those are exposed by any python libs.

Alternatively, you can take advantage of the fact that the global interpreter lock is released for calls to native code. If you're willing to implement your background work in C/C++, you can dynamically link it and invoke it from python. Work done in calls to native functions will be able to run in parallel with python code. Sharing data is more straightforward, but you have to write a bunch of C++, compile it, and get it to dynamically link.

If you hate C/C++, go with multiprocessing. If your background work comes in big monolithic chunks which you're going to end up reading from and writing to disk anyway, go with multiprocessing. If your background work comes in a bunch of bits and pieces which need to be glued together in interesting ways, implement the bits and pieces in DLLs and use python threads for the glue.
> 5 votes

# Answer
So about Python threading, it doesn't do any work concurrently since multiple threads within the same process can only run on 1 core. So all threads within the same process in competition for the same bit of processing power causing the performance issues you described.

The multiprocessing class will utilize multiple cores, since the distributed of the work is then handled by the OS. Sharing data becomes a bit of a problem but I recomend Python's Pipe class.

But to directly answer your question the multiprocessing class will not cause the performance issues threading class is causing you.
> 1 votes

---
Tags: multithreading, terrain-rendering, pygame
---


# Question
Title: How are non-repetitive pixel backgrounds created in 2D games? (e.g., Superbrothers: Sword & Sworcery EP)
What methods are used to create complex, rich, non-repetitive 2D pixel backgrounds in games like Superbrothers: Sword & Sworcery EP? Examining screenshots from the game, I really can't detect tiles anywhere; there's seemingly no repetition:

Are backgrounds like that simply created as large one-of-a-kind images, or are the developers just being extremely clever about their use of repeated sprites and tiles?

Sub-question: I understand that tiles were very important in decades past because of RAM limitations, but is it reasonable to assume that today's games could simply use a single large background image instead? Even on an iOS game like S:S&S EP?

# Answer
I think it's safe to assume these are just images and nothing special is going on in their creation. For memory efficiency it would make sense to chunk up the images and load only the chunks that are currently (or likely to soon be) visible.
> 8 votes

# Answer
It's not a pixel background, but some games like Aquaria do use sprites, but extensively scale and rotate them to create very non-linear/repeating levels from a relatively small set of art assets. See http://www.bit-blot.com/?p=17 for a video of the Aquaria level editor in action.

This kind of layered use of base images allows for interesting effects like focal depth of field, drawing order and parallax effects. Even a game like S&S could utilize this style of level creation to allow pass behind effects as well as parallax.
> 2 votes

# Answer
My Mario clones from school just used a multi-layered tile engine.. Tiles for the foreground (most of them empty ofcourse), then a layer of tiles the player would interact with (the ground mario ran on/into). Then a tile of the background foliage (the 'hills' that you could jump on but not run into them.. not the tops of them, just the filled in 'background' parts that you could run by fit in this bill. And then finally a Back background layer of tiles... For putting together clouds and such.. This is the layer that scrolled at a different speed (smaller tile map as well) to get a bit of parallax scrolling going on.
> 1 votes

---
Tags: 2d, graphics
---


# Question
Title: Collision intepenetration and objects getting stuck (Unity)
I am having what is probably a newbie problem with Unity, but for the life of me, I can't find a decent solution to it. In short: my rigid bodies collide, but sometimes, they interpenetrate and stay stuck.

I am looking for a solution that would either 1- stop the interpenetration from even happening 2- or at least eject the bodies to 'unstuck' the collision.

By making the physics fixed step 0.01 instead of the default 0.02, I can avoid some of the interpenetration. However, that hardly sound like the proper way to fix this problem.

Here is a screen shot of the bodies colliding. The car on the right is shown completely and you can notice that the ones behind have penetrated the others to some extent.

To give more information that could be relevant:

* There is no gravity
* All the objects have rigid bodies
* Their sizes are 3.5 x 6.8 and they are moving at 8 to 50 m/s
* Each object has a conpounded collider made up of 3 box colliders
* If I change the fixed step to 0.01 there is a lot less more interpenetration (as I mentioned). Other physics settings do not seem to have any effect
* The object is moved by setting its velocity in the FixedUpdate function with rigidbody.velocity = XYZ until there is a collision, then there is no more processing done in FixedUpdate at all. I detect the collision with OnCollisionEnter and set a flag.
* I haven't set any collision material, but I can't see that being a factor?

**Solved**

Thanks to everyone who helped me with the issue.

There were a few factors in play. First, there was the scale. What I did to figure this one is create an empty scene and put 2 cubes in there. I varied the size and position of the cubes (from 68x35 to 0.65x0.35 for size and the position by factors or 10 as well) and attached a script to move them, with variation in speed by factors or 10 as well. So all else being equal (same size on the screen and time to cross it), the size of the objects elected a different response to collision: big object got interpenetration, small ones none. I am not familiar enough with Unity to explain the cause of that, but it is reproductible.

A possible second factor was the shape of my colliders and how it may be possible that they screwed up the ejecting part. The colliders I had were not overlapping, so I simplified them to 2 boxes in the shape of a cross.

Finally I was setting the position of the objects manually in FixedUpdate and that caused some problems with interpenetration at lower scale (at higher scale, it didn't appear to matter). I changed that to work with the body velocity and it helped.

# Answer
> 2 votes
Any general rigid-body physics engine should be able to eject interpenetrating bodies given good collision data. Try changing the collision shape of your cars; it sounds like they might be getting stuck due to inward-facing collision points. For example, if your 3 boxes are arranged as front-middle-back then you could have a problem like this:

Note that the rear box of the front car (whichever one that is) is behind the front box of the rear car, so the contact points generated will be facing the wrong way. On the other hand, if you make them out of two intersecting boxes, then there are no such inward faces:

(Similar problems can happen when trying to collide against meshes, since meshes specify surface rather than volume.)

You should also consider whether you really need more than one box to get the gameplay effects you're looking for.

This is all largely speculation since you haven't specified what your collision shape is in detail.

---
Tags: collision-detection, unity
---


# Question
Title: Bad to learn XNA without an amazing foundation on C#?
I've been going though Head First C#, and enjoying it's style of teaching. But I'm into this as a hobby for now, and I'm itching to learn more about games, so I've been diving into Learning XNA 4.0 as well.

Is this a bad idea? Is my lack of C# gonna harm adapting it? 'cause as of now, it feels much more rewarding. Between that and http://rbwhitaker.wikidot.com/2d-tutorials, I've been having more "fun" drawing sprites and animations than making calculators.

# Answer
Why would it be? The best way to learn is to get your hands dirty. Doesn't matter what you are doing you are always going to get better.

Just start small, don't overwhelm yourself with trying to have the most efficient and correct code. As you code and code, you will learn whats right and wrong.

Also, don't be afraid to ask many questions. (at the same time, don't forget to use Google).

Good Luck!
> 4 votes

# Answer
It depends. If you lack programming skills at all, it can be bad. Better learn some basis of it first, then jump into game programming. I didn't know nothing of C# when I started coding with XNA, it was very easy to get everything, but I already had 2 or 3 years of programming skills, with C/C++, VB.NET and Delphi...
> 3 votes

# Answer
In my opinion, what your doing is the best way to learn. You get all the fun of making something interactive right away, while learning new concepts of a programming language. Xna was how I came to learn about C#. Before that I had a beginners knowledge of C/C++. But now I must admit that I'm not a fan of C++ and much prefer the managed environment.

Bottom line, your doing just fine.
> 0 votes

# Answer
I didn't have extensive knowledge on C# nor even Java when I started using XNA. At best, I actually just had an equivalent of a person who just finished beginning Java course knowledge level-wise. But because of this experience in XNA, I actually learned a lot more and it's actually been helping in my courses at school.

Overall what I'm saying is that you'll learn more as you program on it. If you find that you don't know how to implement a feature or how to tackle it, google searching helps. In the end, all I can see when you try to use other things (in this case, XNA) is that you learn more. The more you know and experience, the better you are as a programmer.
> 0 votes

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


# Question
Title: Multiplayer box2d networking for turn based game
I am currently in the planning stages for a 2D game for mobile devices which I will be making in C++ using cocos2d-x. The game will be turn based and each turn will have a phase in which the physics simulations will take place. It will also be cross-platform.

I am new to multiplayer networking and am wondering what the best way to synch the physics would be since Box2d does not behave exactly the same on different devices.

The simulation does not have to occur simultaneously on each device but I do need the results to be exactly the same. Ideally the players will be able to witness, on their own device, the same physics simulation( i.e. motion, bouncing, collisions ) and result that occurred during their opponents turn whenever they decide to start their own turn.

What would be the best way to do this? From my research I've come up with a couple of solutions. Should I write some server code on which I would take user input and handle all of the physics simulation, then send the results to each device? or is there a way I could handle the simulation on one device and send all of the information to the other?

Also how exactly does one send everything that happens during a simulation through the network since I can not run the simulation on each device and be guaranteed the same results? Would I just update the server( or device ) with information of what occurs during every few TimeSteps?

# Answer
> 1 votes
If you want to simulate everything on a server then you better have lots of resources, but you can use a peer model with mobile devices if you have a way to exchange connection information.

I created a multiplayer flash game using Box2D and Cirrus. It was a turn based game as well. Cirrus is a peer-peer model but I wrote some server code for bookkeeping - determining who playing in which 'room', scoreboards etc. The peers would decide who plays which turn by randomly 'drawing straws' and comparing. The client who's turn was the current turn would broadcast its 'move' to the other clients. Simulation would then happen in each client seperately.

The main problem I faced was client disconnections and inaccuracies in simulation in each of the clients. Once in five times there would be slight variations in simulation and the position of one player would be different in the different clients. I tried to solve it by making the clients broadcast their own positions to its peers after each turn was done simulating, but it did not look great since in some clients the position was so dramatically different that it looked jerky. Worse case was when one player was 'dead' in some clients but not on some others.

Simulating in a client whose turn is now and then broadcasting to others the results of simulation might work, if there are no strict time constraints. You should always consider disconnections at every stage.

---
Tags: physics, networking, box2d, multiplayer, client-server
---


# Question
Title: Reflections based on distance from plane
Let's consider, for example, a surface like the volleyball court, we can see that legs and shoes of the players are reflected, with a blur effect, but body and stadium don't (as each object not near to the court).

I've already made a reflection effect, but it works as a specular reflection, and I need to achieve an effect like the photo above. So, I would like to make a reflection that is based on the distance between the object and the plane, in this manner a close object would reflect more than an object that is positioned far away from the plane.

What is the best way to achieve this effect? My first idea was to use the depth value (taken from the reflected camera), and use that value to blend between reflection and court. But I don't know if it's a correct way.

**Edit:** as rendering engine I use Ogre that already provides a reflections system: reflecting the camera through a plane (obviously I can select the models to draw from the reflected camera). After a render to texture pass I can blend the reflected texture with the original plane. So, if possible, I'm looking for a way that best suits my system.

# Answer
> 1 votes
This answer doesn't really achieve what you are looking for, but is still related. If you currently have a constant reflectivity factor, consider replacing it with a one calculated using Fresnel equation. It can also be used for non-refractive materials and it achieves the effect where the surface reflects more when viewed from a lower angle. Check this paper from nVidia for more information. The paper also presents a fine and simple approximation for the function, which in GLSL is:

```
float fresnel(vec3 reflection, vec3 normal, float R0) {
    // float const R0 =  pow(1.0 - refractionIndexRatio, 2.0) /
    //                   pow(1.0 + refractionIndexRatio, 2.0);
    // reflection and normal are assumed to be normalized
    return R0 + (1.0 - R0) * pow(1.0 - dot(reflection, normal), 5.0);
}

// R0 = 0.02 empirically provides good results for my case.
float f = fresnel(reflectionVector, normal, 0.02);
float reflectivity = mix(alpha, 0.0, f);

```

# Answer
> 0 votes
Draw the court itself with no depth output, but the lines and everything else with depth turned on.

Then as a last step draw a very low resolution model mimicking each athlete, mirrored upside down. It's probably best if the low resolution model is rendered with a fake fade the further away from the feet it gets, you don't need to be accurate but just look good.

You can apply blur or leave as a sharp but ghostly render for polished floors.

---
Tags: shaders, graphics-programming, ogre, graphic-effects
---


# Question
Title: What is the cost of distributing through steam?
We are in Pre-alpha stage of a game development project and haven´t yet got reply from Valve about how it works to distribute through Steam. We need this information to do a business model with all the different costs of developing and distributing this game.

So my question is, what is the pricing structure? Do they take a per cent of our sale? If so, how much?

Thanks Felix

# Answer
> 20 votes
I have not worked with Valve or released a game on Steam, but I attended a talk given by some guys that just released their first indie game on Steam.

I doubt you'll hear much from them if you're in pre-alpha. He said that when they first contacted Valve, they were told not to send screenshots or demos or anything due to legal reasons. They didn't get much attention from Valve until they ignored that and started emailing screenshots and demos anyway (they were near the end of beta). Valve liked what they saw and hooked them up.

From what they said, Valve is very friendly towards indie developers. They said selling on Steam has been a great experience and they made back all their development costs within a month of their game being on sale.

However, he said that they get tons of spam to that email address from people who just have game ideas and not an actual game, so if you are in pre-alpha my guess is you'll get the cold shoulder. They have to filter people out somehow. But go back when you've got a solid beta or a demo and they'll probably welcome you with open arms.

# Answer
> 6 votes
I've heard it's around 30%, but like all sites of this type, the actual pricing structures are under an NDA.

# Answer
> 4 votes
When you submit a game demo to valve, make sure it works and looks really nice. Don't send an alpha or anything.

If you're not already known to them, they'll just look at it quickly, and if they don't like what they see, they'll shoot it down. Don't expect any feedback..

So make sure your in game/demo presentation is really good.

# Answer
> 2 votes
A lot of useful information regarding publishing games for Steam

Unfortunately, pricing is one of the things they don't discuss publicly.

---
Tags: valve, costs, steam
---


title: trouble in making a game questions?

text:
# Question
Title: trouble in making a game questions?
all i've a little trouble understanding some concepts while making game please give your suggestions on my questions.

I have a animated sprite image this i want to move this image according to given path. I can get path from

```
    Path path = new Path();
    Point s = new Point(150, 5);
    Point cp1 = new Point(140, 125);
    Point cp2 = new Point(145, 150);
    Point e = new Point(200, 250);
    path.moveTo(s.x, s.y);
    path.cubicTo(cp1.x, cp1.y, cp2.x, cp2.y, e.x, e.y);

    canvas.drawPath(path, paint);

```

these points are hard coded and give different results on different screen.

Q1. How can i make path which is similar in all screen size?

Q2. How can i move my animated sprite image according to given path with the image has it's head according to path?

# Answer
Q1: You could make your points realtive to the actual screenresolution. e.g:

```
int referenceDisplayWidth = 1024
int referenceDisplayWidthHeight = 768
double xFactor = referenceDisplayWidth/(float)framework.getDisplayWidth()
double yFactor = referenceDisplayHeight/(float)framework.getDisplayHeight()

```

Now, multiply all your x-Coordinates with xFactor and y-Coordinates with yFactor. Depending on your used framework, there may be more convinient solutions, like drawing to a solution independent canvas or scaling the whole canvas before drawing it to the screen.

Q2: I guess you want to orientate your image to the normal vector of the curve at each given point. Check your used frameworks documentation.

These are more implementation questions than concept questions, in my opinion. Therefore, your used language and framework may help to receive a higher quality answer.
> 2 votes

---
Tags: sprites, path-finding, movement
---


# Question
Title: "The Game Object" - and component-based design
I've been working on some hobby projects the last 3-4 years. Just simple 2d and 3d games. But lately I have started a bigger project. Soo in the last couple of months I've been trying to design a game object class which can be the base of all my game objects. So after much try & die testing I turned to Google which quickly pointed me to some GDC PDFs and PowerPoints. And now I'm trying to get the grasp of component-based game objects.

I understand that the engine creates a game object and then attaches different components which handles things like health, physics, networking and whatever you make them do. But what I don't understand is how component X knows if Y has changed the state of the object. Like how does the PhysicsComponent know if the player is alive, because the health is controlled by the HealthComponent..? And how does the HealthComponent play the "player-died-animation"?

I was under the impression that it was something like this(In the HealthComponent):

```
if(Health < 0) {
   AnimationComponent.PlayAnimation("played-died-animation")
}

```

But then again, how does the HealthComponent know that the game object it is attached to have a AnimationComponent attached? The only solution I see here is

1. Have a check to see if a AnimationComponent is attached or not (Either inside the component code or on the engine side)
2. Have components require other components, but that seems to fight the whole component-design.
3. Write like, HealthWithAnimationComponent, HealthNoAnimationComponent, and soo on, which again seems to fight the whole component-design idea.

# Answer
In all of your examples, there is a terrible problem. The health component needs to know about every component type that might need to respond to the entity dieing. Therefore, none of your scenarios are appropriate. Your entity has a health component. It has an animation component. Neither depend on or know about the other. They communicate through a messaging system.

When the health component detects that the entity has 'died', it sends an 'I died' message. It is the responsibility of the animation component to respond to this message by playing the appropriate animation.

The health component doesn't send the message directly to the animation component. Maybe it broadcasts it to every component in that entity, maybe to the entire system; maybe the animation component needs to let the messaging system know that it's interested in 'I died' messages. There are many ways to implement the messaging system. However you implement it, the point is that the health component and the animation component never need to know or care if the other is present, and adding new components will never require modifying existing ones to send them appropriate messages.
> 12 votes

# Answer
The way that Artemis solves the problem is to not do processing within Components. Components contain only the data they need. Systems read multiple component types and do whatever processing is necessary.

So, in your case, you may have a RenderSystem that reads in the HealthComponent (and others) and plays the queues up the appropriate animations. Separating data from functions this way makes it easier to keep dependencies properly managed.
> 8 votes

# Answer
In your code you can there are to ways(I used them, possibly some other ways exist) to know if object changed state:

1. Send message.
2. Read directly data from component.

> 1) Have a check to see if a AnimationComponent is attached or not(Either inside the component code or on the engine side)

For this I used, 1. HasComponent function of GameObject, or 2. when you attach component you can check dependencies in some constructing function, or 3. If I know for sure that object has this component, I just use it.

> 2) Have components require other components, but that seems to fight the whole component-design.

In some articles I've read, that in Ideal system components do not depend on each other, but in real life it is not so.

> 3) Write like, HealthWithAnimationComponent, HealthNoAnimationComponent, and soo on, which again seems to fight the whole component-design idea.

It's a bad ide to write such components. In my app I created Health component most independent. Now I am thinking about some Observer pattern that notifies subscribers about some specific event(e.g. "hit", "heal" etc). So AnimationComponent must decide by itself when to play animation.

But when I've read article about CBES it impressed me, so I am very happy now when I use CBES and discover new possibilities of it.
> 6 votes

# Answer
Its like Michael, Patrick Hughes and Blecki says. The solution to avoiding simply moving the problem around is to abandon the ideology that causes the problem in the first place.

Its less OOD and more like Functional Programming. When I started experimenting with Component-Based Design, I spotted this issue down the road. I googled some more, and I found "Functive Reactive Programming" as being the solution.

Now my components are nothing but a collection of variables and fields that describe its current state. Then I have a bunch of "System" classes that update all components that are relevant to them. The reactive part is achieved by running the Systems in a well defined order. This ensures that whatever System is next in line to do its processing and updating, and whatever components and entities it intends to read and update, its always working on up-to-date data.

However, in a way you could still claim that the problem has moved yet again, though. Because what if its not straighforward which order your Systems need to run in? What if there are cyclical relationships and its only a matter of time before you're staring at a mess of if-else and switch statements? Its an implicit form of messaging, no? At first glance, I think its a small risk. Usually, things are processed in order. Something like: Player Input -\> Entity Positions -\> Collision Detection -\> Game Logic -\> Rendering -\> Start over. In that case, you'd have one System for each, provide each System with an update() method, and then run them in sequence in your gameloop.
> 3 votes

---
Tags: architecture, game-mechanics, design-patterns
---


title: How do I create a decal system?

text:
# Question
Title: How do I create a decal system?
I'm currently given the task to design & create a simple decal-system in C++/DirectX.

Does anybody know a great tutorial, article or paper to start with? (Especially the part about 2D-texture to 3D-surface projection and clipping isn't entierly obvious to me.)

I'd also appreciate just simple hints and best-practices.

# Answer
> 5 votes
An example of what you might be looking for:

These forum topics should help you get started:

I am in the middle of writing my decal system (C#, XNA), and it is going pretty well. So let me know if you need some help. Here is a video of it in action: http://www.twitch.tv/battlekiller/b/308505930 . (The decal is the yellow spell circle following the mouse.)

---
Tags: directx, textures, projection, decal-system
---


# Question
Title: Determining Available Recruits in Java Game
I am making a Recruit Army System on my Java Text Based Strategy RPG, so here are the integers by the way:

```
    public int Swordsman; //Price: 10 each
public int Ronin; //Price: 10 each
public int Rider; //Price: 20 each
public int Archer; //Price: 10 each
public int Wizard; //Price: 20 each
public int Mage; //Prince: 20 each
public int Destroyer; //Price: 40 each
public int Soldiers; //Price: 30 each
public int totalarmies = Swordsman+Archer+Wizard+Mage+Destroyer+Soldiers;

```

So first off, I made some dialogues that will display the ones I will recruit:

```
                System.out.println("=========RECRUIT============");
            System.out.println("Coins: " + coins);
            System.out.println("Swordsman - 10 Coins Each");
            System.out.println("Ronin - 30 Coins Each");
            System.out.println("Rider - 20 Coins Each");
            System.out.println("Archer - 10 Coins Each");
            System.out.println("Wizard - 10 Coins Each");
            System.out.println("Mage - 20 Coins Each");
            System.out.println("Destroyer - 40 Coins Each");
            System.out.println("Soldier - 10 Coins Each");
            System.out.println("===========================");

```

Say for example I have the user input how many Swordsman he or she likes to recruit. I set up a Scanner to scan the number the user inputs and say the user inputs 20 (as max).

How can I determine the amount of coins needed to the number of the recruits the user inputs and if the coins I have on my pack can sustain the amount of recruits?

Second question is, how can I limit the user to recruit 20 units max to each class, so that the user can only recruit 20 swordsmen, 20 ronins etc?

Thank you in advance

# Answer
This seems like a *very* rudimentary programming problem and probably off topic for the site.

> How can I determine the amount of coins needed to the number of the recruits the user inputs

coinsRequired = SwordsMen * *playerInputNumber*

> if the coins I have on my pack can sustain the amount of recruits

if( coins \>= coinsRequired ) { ... }

> how can I limit the user to recruit 20 units max to each class

I'd just set up a dictionary of id (type of unit) to int (number of that unit) and keep track of the number of units that way.
> 4 votes

---
Tags: java
---


# Question
Title: What percentage of development time should I spend in balancing?
As an indie developer, I am inclined to release the game as soon as it is 'finished'. In hindsight, most of my games could have used more balancing. I know that there is no fixed answer to this question, but as a thumb rule, what percentage of total development time should be dedicated to game balancing?

# Answer
The most important thing you can do is polish your game, and balance as you polish. I say this because polishing can often encompass balancing. A polished game attracts a lot more attention because it feels and looks better, and shows that the developer paid a great deal of attention to detail. To give an example, Braid could have been called 'finished' in terms of mechanics and puzzles in just the 9 days that Jonathan Blow took to prototype it. The next two or three years were spent improving the art, tweaking and adding puzzles, and refining the mechanics. Each of those things relates to both polishing and balancing.

Depending on what kind of game you're making, balancing may not overlap with polishing as much as that example. Still, I would suggest polishing first, and if you have raw numbers (such as in an RTS game) that need balancing, then go on to do that last.

The amount of time it should take is however long you'd like. Usually once your play testers are satisfied and cannot pick out any broken or overpowered elements, you're set to release. As an indie developer, you have the benefit of setting your own deadlines.
> 8 votes

# Answer
You should aim to balance the game as much as you have to in order to make it fun. While doing so, you should be conscious of the development cost (whether that be in real money or in opportunity cost) in doing so such that, if need be, you can decide that it is "good enough" to ship and still make a profit.

Trying to distill the process down to a numerical rule of thumb is, in my mind, disingenuous because the process will vary widely between developers and games.
> 6 votes

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


title: way to implement a menu -pratical

text:
# Question
Title: way to implement a menu -pratical
i do my first game and already read alot about design strategie, programming style, design .. and so on theoretically it works perfect but in practice i dont know if i do thinks "right"

i have three classes my main which starts the view in this i do all my stuff -currently-

it holds an state variable, it has an onDraw method .. and so on

the third class is the game-thread while my game is running, in here are decisions -depending on my current state- what should be done

```
@Override
public void run() {
    Canvas canvas = null;
    mStartTime = System.currentTimeMillis();
    while (mRun) {
        canvas = mHolder.lockCanvas();
        if (canvas != null) {

            // State Updating State means to manage state transitions, such as a game over, character select or next level.

            switch( mPanel.getModeState() ){
                case Surface.MODE_LOGO_SPLASH :
                break;

                case Surface.MODE_MENU :
                    // the menu

                break;
                case Surface.MODE_LOADING :
                    // loading animation

                break;
                case Surface.MODE_GAME_PLAYING :
                    // game stuff
                                            // GAME START _ RUNNING _ END

                    // Input
                    // AI
                    // Physics

                    // animation
                    //mPanel.animate(mElapsed);
                break;
            }

            // draw everyThing
            mPanel.doDraw(mElapsed, canvas);
            // sound
            // Sound and Video.
            mElapsed = System.currentTimeMillis() - mStartTime;
            mHolder.unlockCanvasAndPost(canvas);
        }
        mStartTime = System.currentTimeMillis();
    }
}

```

my problem is .. the function onDraw draws everything .. including the menu ? this sounds for me like bad code because everytime doDraw is executet, i have to check in this function which state i am currently in .. this cost time, dosent it ?

```
public void doDraw(long elapsed, Canvas canvas) {
    canvas.drawColor(Color.BLACK);

        // currently just gameLayout
        canvas.drawBitmap(background, 0, 0, mPaint);
    gameLayout.draw(canvas);

}

```

would it not be better do implement an other thread which draws the menu ? but if so, how can i overlay the menu afer pause the game ?

:\ thanks for help erwin

# Answer
You have here the rudiments of a normal game loop.

You have your "update" phase.

You have your "draw" phase.

This is the heartbeat of pretty much every game ever.

However.

You haven't QUITE gone far enough yet with abstracting the game state.

Here's what I mean.

Make yourself a GameState interface.

The methods supported are update, draw, along with whatever parameters you find to be necessary for each.

Additionally, there is a method called next, which returns the next game state to run.

Important: each game state updates itself. each game state draws itself.

The game states themselves should be represented in an enum, but could be ints or strings or whatever you please.

Next, make yourself a class for each of your game states that implements the GameState interface.

Now make a collection (prolly a HashMap), populated with the game state and objects representing the game states.

Now your loop looks like:

```
Map<YourEnumType,GameState> stateMachine = new HashMap<YourEnumType,GameState>();
//populate stateMachine here
YourEnumType theGameState = YourEnumType.INITIAL;
while(theGameState!=YourEnumType.FINAL){
    //whatever you do at the start of each loop
    GameState theGameStateObject = stateMachine.get(theGameState);
    theGameStateObject.update();
    theGameStateObject.draw();
    theGameState = theGameStateObject.next();
    //whatever your do at the end of each loop
}

```

For your states, you will need to have (accoring to your post as well as the seemingly obvious states to include:

INITIAL

LOADING

PLAYING

PAUSED

FINAL

Then, when in PLAYING, if the user does whatever is needed to pause the game, you set a field needed to return the value PAUSED from the call to next.

In the PAUSED state, you draw what is normally drawn in PLAYING, but on top of it you draw the ui you are interested in drawing.

There's a little more to it, for example having some "enter" and "leave" methods for the GameState objects, but the idea should be effectively visible.

Hope this helps.
> 2 votes

---
Tags: gui, game-loop
---