# Question
Title: Why RenderTarget2D overwrites other objects when trying to put some text in a model?
I am trying to draw an object composited by two cubes (A & B) (one on top of the other, but for now I have them a little bit more open). I am able to do it and this is the result.

(Cube A is the blue and Cube B is the one with brown text that comes from a png texture)

But I want to have any text as parameter in the cube B. I have tried what @alecnash suggested in his question, but for some reason when I try to draw cube B, cube A dissapears and everything turns purple.

This is my draw code:

```
public void Draw(GraphicsDevice graphicsDevice, SpriteBatch spriteBatch, Matrix viewMatrix, Matrix projectionMatrix)
        {
            graphicsDevice.BlendState = BlendState.Opaque;
            graphicsDevice.DepthStencilState = DepthStencilState.Default;
            graphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
            graphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;

            // CUBE A
            basicEffect.View = viewMatrix;
            basicEffect.Projection = projectionMatrix;
            basicEffect.World = Matrix.CreateTranslation(ModelPosition);
            basicEffect.VertexColorEnabled = true;
            foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
            {
                pass.Apply();
                drawCUBE_TOP(graphicsDevice);
                drawCUBE_Floor(graphicsDevice);
                DrawFullSquareStripesFront(graphicsDevice, _numStrips, Color.Red, Color.Blue, _levelPercentage);
                DrawFullSquareStripesLeft(graphicsDevice, _numStrips, Color.Red, Color.Blue, _levelPercentage);
                DrawFullSquareStripesRight(graphicsDevice, _numStrips, Color.Red, Color.Blue, _levelPercentage);
                DrawFullSquareStripesBack(graphicsDevice, _numStrips, Color.Red, Color.Blue, _levelPercentage);

            }

            // CUBE B
            // Set the World matrix which defines the position of the cube
            texturedCubeEffect.World = Matrix.CreateTranslation(ModelPosition);
            // Set the View matrix which defines the camera and what it's looking at
            texturedCubeEffect.View = viewMatrix;
            // Set the Projection matrix which defines how we see the scene (Field of view)
            texturedCubeEffect.Projection = projectionMatrix;
            // Enable textures on the Cube Effect. this is necessary to texture the model
            texturedCubeEffect.TextureEnabled = true;
            Texture2D a = SpriteFontTextToTexture(graphicsDevice, spriteBatch, arialFont, "TEST ", Color.Black, Color.GhostWhite);
            texturedCubeEffect.Texture = a;
            //texturedCubeEffect.Texture = cubeTexture;
            // Enable some pretty lights
            texturedCubeEffect.EnableDefaultLighting();
            // apply the effect and render the cube
            foreach (EffectPass pass in texturedCubeEffect.CurrentTechnique.Passes)
            {
                pass.Apply();
                cubeToDraw.RenderToDevice(graphicsDevice);
            }

        }

    private Texture2D SpriteFontTextToTexture(GraphicsDevice graphicsDevice, SpriteBatch spriteBatch, SpriteFont font, string text, Color backgroundColor, Color textColor)
    {
        Vector2 Size = font.MeasureString(text);
        RenderTarget2D renderTarget = new RenderTarget2D(graphicsDevice, (int)Size.X, (int)Size.Y);
        graphicsDevice.SetRenderTarget(renderTarget);

        graphicsDevice.Clear(Color.Transparent);

        spriteBatch.Begin();
        //have to redo the ColorTexture
        //spriteBatch.Draw(ColorTexture.Create(graphicsDevice, 1024, 1024, backgroundColor), Vector2.Zero, Color.White);

        spriteBatch.DrawString(font, text, Vector2.Zero, textColor);
        spriteBatch.End();

        graphicsDevice.SetRenderTarget(null);

        return renderTarget;
    }

```

The way I generate texture with dynamic text is:

```
 Texture2D a = SpriteFontTextToTexture(graphicsDevice, spriteBatch, arialFont, "TEST ", Color.Black, Color.GhostWhite);

```

After commenting several parts to see what caused the problem, it seems to be located in this line

```
graphicsDevice.SetRenderTarget(renderTarget);

```

# Answer
> 1 votes
That purple colour is the "uninitialized surface" colour.

Basically whenever you call `GraphicsDevice.SetRenderTarget`, the render target that you set gets cleared (by default). In this case, the back-buffer counts as a render target (setting `null`).

You *could* set `RenderTargetUsage.PreserveContents` on the backbuffer. But preserving the contents of a render target is slow on Xbox 360 and Windows Phone. The default is to clear in order to be fast on those devices (and Windows matches that behaviour to make your life easier when porting).

The *recommended* way to solve this is to order your drawing so that you fill your render targets before you draw anything to the backbuffer.

This is explained in detail in this blog post. And also in my answer here.

---

Also it looks like you are creating a fresh render-target each frame. That's a big no-no. Create it once and re-use it!

---
Tags: xna-4.0
---


# Question
Title: What is a good format for a 3d topview map?
I am building a 3d topview game like GTA2. In this game the ground is mostly one level (except for tunnels and highways). Most of the ground is also city so the ground is usually covered by either roads or buildings. The buildings are simple 3d models which the player can walk around on. Most of the gameplay is 2d.

How should I model the map? I have considered the following options:

* Bitmaps, I think this gives problems when I want to add data smaller than a tile. Also the problem of bridges and tunnels seems hard to solve with this.
* Polygons, define all roads, terrain types, buildings with polygons and save that along with physics and texture information.

What approach would you take or have you ever implemented this or know of an implementation?

# Answer
> 2 votes
Are you going to use a terrain system ? or is it just flat ?

Bridges and tunnels do add complexity. To have bitmaps represent bridges and tunnels you could perhaps use a 2nd bitmap layer or even one of the channels to represent a second ground layer. (i just noticed that zacharmarz mentioned these considerations) I'm not sure, as there is always a way to make something work, but I'd imagine any commercial game using such sophisticated geometry would utilize a 3d engine. So unless you're an experienced game developer, I'd ditch the bridges and tunnels idea. At least until you've got some other more basic requirements met. Oh, unless those bridges and tunnels are part of the only traversable layer, then it's easier

You can add texture data onto the ground smaller than a tile. That's not a problem. And you can have objects (other than buildings) that are smaller than a tile, because any objects including buildings will be geometry which you have defined. All this talk is speculative though, because the solution options you have are numerous. It would be totally possible to build a bitmap based map system as long as you are clever (and patient) enough to overcome all the challenges. Indeed a lot of game terrains (2d & 3d) are built using heightmap's blendmap's ect which are simply bitmaps. BUT, if you want the power to be able to drop an object onto the ground, anywhere, it makes more sense to me to have in addition to the bitmap (defining ground textures / buildings or whatever) a collection of objects which have location properties : float x, float y, float z or Vector3 position. And run through that collection as well, rendering at their positions, just as you do for your avatar/player character.

# Answer
> 1 votes
I would prefer bitmaps, which will hold information about objects (buildings, roads, water, etc.).

If you have problem with tile / pixel size, you can separate "city / map" into several big tiles and each tile will have separate bitmap.

Problems with tunels and bridges can be solved by using more than one bitmap for tile / map. Or by using different color components. When you will be rendering you world, you for example just look, if there is no bridge over water, you are just rendering.

# Answer
> 1 votes
You can also do a hybrid approach: 3d with modular pieces. Make a set of 3d "tiles" and piece them together in a level editor. That gives you the fast editing speed of bitmaps but gives you the flexibility to add bridges and tunnels and custom set pieces.

Neverwinter Nights uses a system like this, if you're looking for inspiration.

---
Tags: maps
---


# Question
Title: Putting a Java/Slick game on your website?
I've made a simple little 2D game in Java using Slick and I want to embed it in my website. I'm just a little confused as to how to go about it, I'm guessing I need to export it as a WAR file?

Sorry if this isn't really specific but oddly enough I couldn't find *any* information on this subject. I think I may lack the basic vernacular to describe my question, because most of my Google and other searches turn up completely unrelated results any help would be appreciated, I just need a starting point.

# Answer
I think what you are looking for is "Java applet".

So I just did a fast Google search for "java slick applet" and found this: http://ninjacave.com/slickapplet
> 1 votes

---
Tags: java, slick
---


title: LWJGL - Mixing 2D and 3D

text:
# Question
Title: LWJGL - Mixing 2D and 3D
I'm trying to mix 2D and 3D using LWJGL.

I have wrote 2D little method that allow me to easily switch between 2D and 3D.

```
protected static void make2D() {
    glEnable(GL_BLEND);
    GL11.glMatrixMode(GL11.GL_PROJECTION);
    GL11.glLoadIdentity();
    glOrtho(0.0f, SCREEN_WIDTH, SCREEN_HEIGHT, 0.0f, 0.0f, 1.0f);

    GL11.glMatrixMode(GL11.GL_MODELVIEW);
    GL11.glLoadIdentity();
}

protected static void make3D() {
    glDisable(GL_BLEND);
    GL11.glMatrixMode(GL11.GL_PROJECTION);
    GL11.glLoadIdentity(); // Reset The Projection Matrix
    GLU.gluPerspective(45.0f, ((float) SCREEN_WIDTH / (float) SCREEN_HEIGHT), 0.1f, 100.0f); // Calculate The Aspect Ratio Of The Window

    GL11.glMatrixMode(GL11.GL_MODELVIEW);
    glLoadIdentity();
}

```

The in my rendering code i would do something like:

```
make2D();
//draw 2D stuffs here

make3D();
//draw 3D stuffs here

```

What i'm trying to do is to draw a 3D shape (in my case a quad) and i 2D image. I found this example and i took the code from `TextureLoader`, `Texture` and `Sprite` to load and render a 2D image.

Here is how i load the image.

```
TextureLoader loader = new TextureLoader();
Sprite s = new Sprite(loader, "player.png")

```

And how i render it:

```
make2D();
s.draw(0, 0);

```

It works great.

Here is how i render my quad:

```
glTranslatef(0.0f, 0.0f, 30.0f);
glScalef(12.0f, 9.0f, 1.0f);
DrawUtils.drawQuad();

```

Once again, no problem, the quad is properly rendered.

*DrawUtils is a simple class i wrote containing utility method to draw primitives shapes.*

Now my problem is when i want to mix both of the above, loading/rendering the 2D image, rendering the quad. When i try to load my 2D image with the following:

```
s = new Sprite(loader, "player.png);

```

My quad is not rendered anymore (i'm not even trying to render the 2D image at this point). Only the fact of creating the texture create the issue. After looking a bit at the code of `Sprite` and `TextureLoader` i found that the problem appears after the call of the `glTexImage2d`. In the `TextureLoader` class:

```
glTexImage2D(target,
        0,
        dstPixelFormat,
        get2Fold(bufferedImage.getWidth()),
        get2Fold(bufferedImage.getHeight()),
        0,
        srcPixelFormat,
        GL_UNSIGNED_BYTE,
        textureBuffer);

```

Commenting this like make the problem disappear. My question is then why? Is there anything special to do after calling this function to do 3D? Does this function alter the render part, the projection matrix?

# Answer
> 3 votes
Try disabling textures before you draw the quad. If the corner of the texture is transparent, and the texture is still bound when you draw the quad, maybe the whole quad is being drawn with the transparent pixel.

---
Tags: opengl, java, lwjgl
---


# Question
Title: Triggering State Changes with Health Counter
I'm developing a game where the player changes states as their health decreases. Below 50, it should trigger animation1. Below 30, it should trigger animation2.

The problem is, I only want to trigger animation1 once. But my game timer is checking every "frame", so it's triggering animation1 every cycle below 50. I only want it to trigger once, then not again until it's gone over 50 and then naturally decreased back to below 50.

**Are there any tried and true strategies for triggering state changes as a timer counts down (without the over-triggering problem)?**

I thought I could say:

```
if (health == 50)
 animation1.play();

```

but sometimes, health never equals exactly 50, so it will skip right past that statement.

# Answer
> 2 votes
Really, this comes down to your given implementation of game-logic.
There's nothing in particular that is right or wrong, here.

Personally, I'd be using some sort of event-driven system (like a Moderator/Publisher+Subscriber), inside of my player/enemy/vehicle, and using components like a health component and an animation component.

Inside of a `takeDamage` method, I might do my regular health stuff, and while doing the regular checks (ie: not dead), add in one additional set of checks to see if that particular instance passed a "pain threshold".

In an enumerator or an array or any other way you're going to store your states, you might do a check like:

```
if (this.current_health > pain_threshold_1 &&
    this.current_health - damage_amount < pain_threshold_1) {
    this.mediator.notify("player_state_change", "hurt");
}

```

The animation module would be listening for the `"player_state_change"` event, and would change the current animation.

The opposite check could be added to an `addHealth` method.

This might be overkill for a ***Pong***-clone...

# Answer
> 0 votes
If you use a flag to track whether your threshold has been crossed, and another to indicate whether you should play the animation in the current frame, you can do what you're trying to accomplish. If you start out like this:

```
// start of program
bool play_animation1 = false;
bool greater_than_50 = true;

```

Then in your game's loop do this every frame:

```
// game loop
if(health <= 50){
    if(greater_than_50){
        play_animation1 = true;
        greater_than_50 = false;
    }
}
else if(health > 50){
    greater_than_50 = true;
}

...

// animations
if(play_animation1){
    // animation1.play() is called ONCE:
    // play_animation1 = false;
    animation1.play();
}

...

// cleanup
if(animation1.over()){
    // animation1.play() is called CONTINUOUSLY:
    play_animation1 = false;
}

```

So going into the game loop, if play\_animation1 and greater\_than\_50 start false and true, respectively. Their values then both invert, and the animation starts playing. When the animation is finished, the play\_animation1 flag is set to false. They'll now both stay false until the player's health rises above 50, and then the process is able to repeat. The flags should probably be private members of your player class, if that's applicable.

# Answer
> 0 votes
What Eric has suggested to you is basically a FSM implementation without the framework. If you find yourself in a situation where you often need actions to occur when state is changing, implementing (or using) a FSM framework is a good idea. Given the right setup then you would simply run the update method on your state machine, and it would trigger the actions you would need per the state in your application.

You could also implement a `TrueOnce` object that takes a predicate that is checked each frame. In pseudo/c#:

```
//given TrueOnce playAnimation1 = new TrueOnce(()=>health<=50);
if (playAnimation1.isTrue()) {
    //play the animation
}

```

This uses a lambda function, I could help you write an implementation if you tell me what language you're using.

The other thing you could do if this is not likely to become a pattern and you just want something quick that works, try this:

```
//given animation1 and animation2 are global variables initialized to null
if (health<=50 && animation1==null) {
    animation1= new Animation1(); //whatever
    animation1.play();
} else if (health<=30 && animation2==null) {
    animation2= new Animation2(); //whatever
    animation2.play();
}

```

---
Tags: game-loop
---


# Question
Title: Why does my VertexDeclaration apparently not contain Position0?
I'm trying to get my code from calling each individual draw call down to using at least a VertexBuffer, and preferably an indexBuffer, but now that I'm attempting to test my code, I'm getting the error:

> The current vertex declaration does not include all the elements required by the current vertex shader. Position0 is missing.

Which makes absolutely no sense to me, as my VertexDeclaration is:

```
public readonly static VertexDeclaration VertexDeclaration
    = new VertexDeclaration(
        new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
        new VertexElement(sizeof(float) * 3, VertexElementFormat.Color, VertexElementUsage.Color, 0),
        new VertexElement(sizeof(float) * 3 + 4, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0)
        );

```

Which clearly contains the information. I am attempting to draw with the following lines:

```
VertexBuffer vb = new VertexBuffer(GraphicsDevice, VertexPositionColorNormal.VertexDeclaration, c.VertexList.Count, BufferUsage.WriteOnly);
IndexBuffer ib = new IndexBuffer(GraphicsDevice, typeof(int), c.IndexList.Count, BufferUsage.WriteOnly);

vb.SetData<VertexPositionColorNormal>(c.VertexList.ToArray());
ib.SetData<int>(c.IndexList.ToArray());

GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vb.VertexCount, 0, c.IndexList.Count/3);

```

Where c is a Chunk class containing an 8x8x8 array of boxes.

Full code is available at https://github.com/mrbaggins/Box/tree/ProperMeshing/box/box.

Relevant locations are Chunk.cs (Contains the VertexDeclaration) and Game1.cs (Draw() is in Lines 230-250). Not much else of relevance to this problem anywhere else. Note that large commented sections are from old version of drawing.

**EDIT: I condensed the problem down even further, the following draw code won't even run, with the same error:**

```
VertexBuffer vb = new VertexBuffer(GraphicsDevice, VertexPositionColor.VertexDeclaration, 3, BufferUsage.WriteOnly);
VertexPositionColor[] temp = {
            new VertexPositionColor(new Vector3(-3.0f,-3.0f,3.0f), Color.Blue),
            new VertexPositionColor(new Vector3(0.0f,0.0f,0.0f), Color.Blue),
            new VertexPositionColor(new Vector3(1.0f,1.0f,1.0f), Color.Blue) };

vb.SetData<VertexPositionColor>(temp);
GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);

```

# Answer
> 2 votes
You need to tell the GraphicsDevice which IndexBuffer and VertexBuffer to use.

```
GraphicsDevice.Indices = ib;
GraphicsDevice.SetVertexBuffer(vb);

```

Place those 2 lines before your draw call.

---
Tags: xna, 3d, graphics
---


# Question
Title: Component based design, but components rely on each other
I've begun stabbing at a "Component Based" game system.

Basically, each entity holds a list of components to update (and render) I inherit the "Component" class and break each game system into it.

Examples:
**RenderComponent** \- Draws the entity
**MovementComponent** \- Moves the entity, deals with velocity and speed checks
**DamageComponent** \- Deals with how/if the entity gets damaged...

So, my system has this:
**MovementComponent**
**InputComponent**

Now maybe my design is off, but the InputComponent should say things like

```
if (w key is down)
    add y speed to movement

if (x key is down)
    Trigger primary attack

```

This means that the InputComponent sort of relies on these other components. I have to do something alone the lines of:

```
if (w key is down)
{
    MovementComponent* entityMovement = mEntity->GetMovement();
    if (entityMovement != NULL)
        add y speed to movement
}

```

which seems kinda crappy every update.

Other options? Better design? Is this the best way?

Thanks!

# Answer
"Input" isn't really a feature, it's data that components can use. The way I handle input in my game's component-based entity system is that I send a `UserInputMessage` to all components, and they can manage it themselves.

If you don't have a messaging system, just add a virtual method to your `Component` class that takes in the current keyboard/mouse state and add it in later.

As for component dependency in general, you can send a message to all the components in an entity when a component is added or removed, and those components can store the reference. That way you aren't constantly requesting different component types.

Again, if you don't have a messaging system, just make it a virtual method.

**EDIT:**

In general, the purpose of a component-based entity system is to decouple features and functionality from each other. Obviously, when you build the system up and start working on the actual game, there are going to be some dependencies, but when you see that a component is a dependency of basically every other component, you're defeating the purpose of the entire system and you should think about other implementations that reduce inter-component dependencies.

I've found that typically messages fit the role of things that shouldn't be components.
> 3 votes

---
Tags: c++, architecture, component-based
---


# Question
Title: OpenGL quake 3 shader file for objects (for trees)
I decided to add to my game few trees, I already quake 3 model loader (md3) its for characters and method for texture drawing is store in \*.ini file. I found a package of trees in MD3 and I have no problem with loading model alone, but there is a \*.shader file and i have no idea how to load it to draw texture properly.

Tree pack: http://www.custommapmakers.org/wiki/index.php/Models:GR\_Trees\_set

I do not have to use exactly this format, I can write another loader, but trees in \*.obj or .3ds look even harder

# Answer
The quake 3 "shader" is basically just a description of the rendering parameters, and has little or nothing to do with opengl shaders. Here's an example from your tree package:

```
models/mapobjects/GR_trees/tree6
{
    cull none
    nopicmip

    {
        map models/mapobjects/GR_trees/tree6.tga
        alphaFunc GE128
        depthWrite
        rgbGen vertex
    }
}

```

Many of the things listed there are pretty obvious - disable clipping, use tree6.tga as texture, have depth write enabled.. as for the rest, you might want to look up the reference:

http://toolz.nexuizninjaz.com/shader/
> 1 votes

---
Tags: opengl, quake3, model-loader
---


# Question
Title: Unity gizmos vs. referenced game objects
I'm designing a Unity script that I intend to be highly reusable and as easy as possible to setup within the editor. To this end, a number of properties of this script really need some kind of visual representation on screen.

It is an unresolved question to me whether the design of the script should require references to placeholder game objects, *OR* just `Vector3`'s and `float`'s that have associated gizmos drawn for them.

Normally a gizmo would be a natural choice, except that Unity gizmos are not directly manipulable (as far as I can tell). Because of this shortcoming I'm having to consider whether depending on references to placeholder game objects is a more designer-friendly approach ultimately, in spite of the extra setup required, and that it might be counter-intuitive when the placeholder game objects disappear at run-time (which my script would do).

Is there a community standard or preference here in this case? Can a Unity-experienced game programmer / designer speak to which approach they feel is more intuitive or more convenient to setup, when using a 3rd party script? Or is this just splitting hairs as long as I ship an example prefab with my script?

# Answer
> 1 votes
I don't know if there's a community standard. I'd say you should either go with whatever you think will be easier to work with, *or* you could have someone else actually try it, just to get input from someone who haven't been looking at the code for months/weeks/hours.

# Answer
> 0 votes
I hope I understand what you're looking for now. It sounds like gizmos is probably what you want to be using. Though, since your description isn't very specific, it's hard to know for sure. It would also be a bit tough to offer specific suggestions on how to use them.

You can do things like use the `MonoBehaviour.OnDrawGizmos` function (link) in your scripts to add extra visual representation in the scene editor of various object properties. It automagically updates gizmos in real time based on changes you make to the object's properties in the inspector. It's also handy to use since the visual effects are not included in a build of the game so you don't have to worry about cleaning up superfluous objects by hand before build-time or by *ad hoc* script at run-time.

For example, in a racing game I worked on a while ago, I used spheres (with `Gizmos.DrawWireSphere`) and lines (with `Gizmos.DrawLine`) to draw the size of and connections between AI trucks' navigation points. It made it much easier to lay out and connect the waypoints and ensure they were properly sized to get the effect we wanted. I also drew lines from the AI trucks to their destinations to make sure they were behaving properly during the game.

---
Tags: unity
---


# Question
Title: Texturize a shape of multiple triangles in 2D
This is an example of a shape consisting of multiple points, triangles and eventually a shape:

**Red Dots = Vector3 (X, Y, Z) or Vector2 (X, Y)**

If I have a Texture of a certain size, how do I texturize this area in the best way so that the texture inside the shape matches the shape and does not overlap anywhere? Perhaps also with a chance to scale the texture in case it's too small or to big for the shape, but still so that it gets rendered correctly.

Do I treat the shape as a rectangle? Figure out it's 4 corners? Or do I calculate the distance between Center - (Texture Width / 2) and Point (to see how "many" times the texture can fit between on that axis to estimate at what Coordinates the Texture should be at that certain point?

I've looked at Texture Mapping but haven't found any concrete examples that it explains it well, it's also confusing with 0.0-1.0 values for Texture Coordinates.

# Answer
**Solution:**

```
public static class MappingHelper
{

    public static VertexPositionTexture[] TextureMapping(VertexPositionTexture[] vertices, float scale = 1f)
    {

        bool initialized = false;

        float x, y;
        float lX = 0, hX = 0, lY = 0, hY = 0;

        for (int i=0; i < vertices.Length; i++)
        {

            x = vertices[i].Position.X;
            y = vertices[i].Position.Y;

            if (!initialized)
            {
                hX = x;
                lX = x;
                hX = y;
                hY = y;

                initialized = true;
            }
            else
            {
                if (x > hX)
                {
                    hX = x;
                }
                else if (x < lX)
                {
                    lX = x;
                }

                if (y > hY)
                {
                    hY = y;
                }
                else if (y < lY)
                {
                    lY = y;
                }
            }

        }

        float width = (Math.Abs(lX) + Math.Abs(hX)) / scale;
        float height = (Math.Abs(lY) + Math.Abs(hY)) / scale;

        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i].TextureCoordinate.X = vertices[i].Position.X / width;
            vertices[i].TextureCoordinate.Y = vertices[i].Position.Y / height;
        }

        return vertices;

    }
}

```
> 0 votes

# Answer
This is the effect that will occur if you treat the shape as a rectangle, and use its bounding box as the 0,0 -\> 1,1 mapping:

This is your texture: This is your shape with texture coords mapped to bounding box(approximate guesses shown): This is the final result:

As you can see you've basically sliced a shape out of the original texture. If that's not what you want to do, you'll need to find some other mapping that makes sense for your particular object.
> 2 votes

---
Tags: xna, textures, normal-mapping
---


# Question
Title: How do I add AndEngine documentation in Eclipse?
I am very new to AndEngine. I have just downloaded the full documentation file, but I can't attach it to Eclipse. How can I do that?

# Answer
Here is detailed how-to: http://www.vogella.com/articles/Eclipse/article.html#classpath\_jarjavadoc
> 1 votes

# Answer
Please use this Andengine extension. This project comes with java documentations for many of the importatnt andengine functions. Its very useful. Plus you can join to update the docs. Checkout here :

```
https://github.com/digitalheir/AndEngine.git

```
> 0 votes

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


# Question
Title: If I use my own normal values, should I turn off winding order culling?
I've discovered that I managed to program a series of boxes with indexed vertices in such a way that every other triangle (Half of each face) has a backwards winding order.

As a result, XNA is culling half of them.

However, my Vertex objects contain normal data that I have explicitly set, and I am going to implement my own backface culling shortly to reduce the size of the VertexBuffer.

Should I turn off winding order culling and manage it myself, or should I make sure the winding order is consistent and let XNA handle it?

# Answer
you won't be able could cull backfaces any where near as quick as the GPU. Especially if you are modifying or recreating the vertex buffer or index buffer on frame-by-frame basis.

I would either;

1. turn off backface culling (at least for the boxes) and live with the extra triangles being drawn (it'll still be much, much faster than your custom backface culling)
2. fix your winding order
> 6 votes

---
Tags: xna, 3d, culling
---


# Question
Title: Collision resolution - Character walking on ascendent ground
I don't know if the solution to this problem is quite straight-foward but I really don't know how to handle collision resolution on a game where the player walks on an ascendent floor which is not flat. How can the player position itself on the y axis depend on the ground x and z (opengl coords)? What if the floor's slope is too much and the player can't go up, how do you handle that?

I don't need any code, just a simple explanation would be great.

# Answer
There are a few ways to tackle this problem. Once he has hit the slope, you could

1. Change the direction he moves from only in the x-z plane to the cross product of the face's normal and the player's "strafe right" vector, (yielding a vector parallel to the face).
2. When resolving collisions, move the player along the slope's normal to get him out of the ground. Every frame, he will move straight forward into the slope, then the collision will push him up and back out of the ground, so he will ascend.
3. Change the direction he moves from his current "forward" vector to his forward vector projected onto the plane of the slope. This is similar to option 1.

To determine if the slope is too steep, you can

1. Take the dot product of the slope's normal and the player's standard "forward" vector (both normalized), and ensure it is not less than some threshold (around -0.6 is probably getting too steep, -1 would be walking straight into a wall).
2. Take the dot product of the standard "forward" vector and the new vector the player would take instead, if using option 1 or 3 from before. Ensure that this dot product is less than some threshold (1 is walking straight forward along a flat surface, 0.5 would be walking up a moderate slope, and 0 would be walking straight into a wall).
> 2 votes

---
Tags: opengl, collision-detection, collision-resolution
---


title: Jump pads problem

text:
# Question
Title: Jump pads problem
I'm trying to make a character jump on a landing pad who stays above him. Here is the formula I've used (everything is pretty much self-explainable, maybe except `character_MaxForce` that is the total force the character can jump):

```
deltaPosition = target - character_position;
sqrtTerm = Sqrt(2 * -gravity.y * deltaPosition.y + MaxYVelocity * character_MaxForce);
time = (MaxYVelocity - sqrtTerm) / gravity.y;
speedSq = jumpVelocity.x * jumpVelocity.x + jumpVelocity.z * jumpVelocity.z;

```

If `speedSq < (character_MaxForce * character_MaxForce)` we have the right time so we can store the value:

```
jumpVelocity.x = deltaPosition.x / time;
jumpVelocity.z = deltaPosition.z / time;

```

Otherwise we try the other solution:

```
time = (MaxYVelocity + sqrtTerm) / gravity.y;

```

and then store it:

```
jumpVelocity.x = deltaPosition.x / time;
jumpVelocity.z = deltaPosition.z / time;
jumpVelocity.y = MaxYVelocity;

rigidbody_velocity = jumpVelocity;

```

The problem is that the character is jumping away from the landing pad or sometime he jumps too far never hitting the landing pad.

# Answer
> 2 votes
You know whether the landing path is left or right by comparing the "x" value. Or you could simply calculate a default trajectory between the two pads. But if you don't want to couple the jump and landing pads then you could simply specify a direction vector in your jump pad and a scalar ( a multiplier ) that acts as a velocity to your character making him jump in a certain direction. Tweaking the scalar and direction should give you the right trajectory.

And by default trajectory I mean using a Quadratic Bezier curve. You know the starting point(jump pad) and the end point(landing pad). Using the control point, which can never be lower than the highest pad, to define your "curve".

Look at the quadratic formula, it's very simple. ( this will only give you the curve though) Using "t" to trace the curve (which is between 0 an 1 ).

---
Tags: physics, jumping
---


# Question
Title: Geometry System of Populous: The Beginning
I want to to develop a game like Populous: The Beginning with my friend. But we could not find out what type of geometry they have used for the world.

We know that \- all tiles have the same size \- all tiles are squares

So.. It cannot be a Icosahedron, because there are triangles, nor cant it be a standard sphere geometry, because not all tiles have the same size.

Can someone help me?

# Answer
> 6 votes
Triangles you are seeing are likely just a product of the rendering system -- everything, in the end, *has* to be broken down into triangles for rendering.

I suggest you do this: search google (images) for "sphere tessellation". You will get an idea of the many, many ways of doing this. Your game does not need to be tessellated in exactly the same way as Populous: The Beginning (which, by the way, is a great game which I love). Meaning you don't even need to use square tiles, if you don't want to; you could use any hexagons, triangles, pentagons, arbitrary quadrilaterals like kites, or even voronoi tessellation (irregular, non-repeated polygons).

What's important in any tessellation used for game logic is *connectivity*, i.e. the fact that your "grid" forms a (somewhat) connected graph for movement purposes.

EDIT: Probably what they've done is something a little like StarControl's melee -- they actually have a wrapping 2D grid (modulo in x and y). Then, when you view the sphere, you can only see one hemisphere at once, which makes it possible to map the tiles without too much noticeable distortion. And at a closer zoom, all would look perfect.

# Answer
> 14 votes
The problem here is that Populous maps are not spheres at all. They're a Torus, more analogous to a flat torus manipulated on screen to look like a sphere than an actual sphere.

For example:

* Populous maps are squares when viewed outside of the populous engine
* Populous maps in game are visibly warped to show/hide the curvature by moving from the normal to the close up/overhead view
* When viewing the overhead globe, the terrain is visibly warped to ensure a spherical appearance
* One can navigate around the world using non-euclidian geometry

> The game is played from a third-person perspective with the camera at a variable height and capable of rotating 360°, enabling the player to quickly move across the planet's terrain. While the terrain's topology is a torus, the map is locally projected onto a sphere to give the illusion of a planet. On maps where there is no fog of war, players can see what opponents are doing at any time. Extensive support for 3D acceleration enables the player to view the game in 16-bit or 32-bit colour.\[10\] The landscape and real-time structure building and follower movement are also shown.

Also, notice here:

If the overview is of half the planet, as it the minimap, why does the minimap show so much more water? And why does the water texture not reflect the true proportions of a sphere by showing an almost side on view at the edges?

Also as noted in comments on the other question, notice in this screenshot the planet is perfectly round:

If it were a true sphere, we'd be able to see hills and objects sticking up from the edge of the planet. For example, here's Planetary Annihilation, see the trees and cliffs jutting out over the horizon:

Instead, for a modern game I would advise tessellating an icosahedron. You'll find many questions on SO on how to do that in a programming language of your choosing

---

### But Triangles?

Yes! It's possible the engine uses quads but quads are generally split into triangles by the drivers and graphics card, and quads have downsides. Games built in the last 20 years will be using triangles

---
Tags: 3d, geometry
---


title: HTML5 as application for tablets?

text:
# Question
Title: HTML5 as application for tablets?
I'm looking at creating a tablet application (iPad, Nexus, Surface...). I've heard it's possible to create it using HTML5 canvas. I was wondering if it was limited to canvas, if div/input/table can also be used.

Can a normal HTML page be used as an application for the Apple, Microsoft, Android store?

# Answer
After looking around and with the comments, I learned that I need something to put a native front end over the html applications. There are a lot of different platform that support a lot of different systems (ex: Cordova).
> 2 votes

# Answer
For the Android Store (Google Play), you will need a small portion of Java code.

To display the HTML in your application, you can use a WebView: http://developer.android.com/reference/android/webkit/WebView.html
> 1 votes

---
Tags: javascript, html5, mobile
---


# Question
Title: Process of getting DEJUS rating (Brazil)?
I would like to get DEJUS rating for my HTML5 game on the Firefox Marketplace, so that I can tell Mozilla to make the game available to users in Brazil. I want the game to be rated as: *Livre (general)*

**Can non-Brazilian citizens request ratings from DEJUS? If so, what documents need to be provided, and in which language?**

What I have found so far:

# Answer
> 15 votes
My experience:

* **2012-11-26 CET**: I called DEJUS (+55.61.2025-9115), and I was connected to someone who spoke fluent English. Things look good:

+ It is *not* necessary to be a citizen of Brazil or to have a company registered in Brazil in order to apply for a rating. In this case, I was told, one just leaves the field *CPF/CNPJ* empty.
    + I asked if it is OK to submit the game synopsis in English: Yes it is!
* **2012-11-28 CET**: I sent the following documents (personal address hidden):

Destination address:

*Departamento de Justiça, Classificação, Títulos e Qualificação*
***Coordenação de Classificação Indicativa***
*Esplanada dos Ministérios, Bloco T,*
*Ministério da Justiça, Anexo II, Sala 321*
*CEP 70064-901 BRASILIA/DF*
*BRAZIL*
* **2013-02-01 CET**: After asking about the rating the day before, I got an email telling me that DEJUS normally gives no personal feedback. One is supposed to check the rating in the *Public Journal*, which I was not aware of. In fact, the rating has already been published on 2012-12-24, as requested as *livre*:

---
Tags: legal, marketing, content-rating
---


# Question
Title: How do I modify a Boids algorithm to be player controlled?
Found source code on Boids in C#.

http://3carrotsonastick.wordpress.com/2012/11/01/boids-in-c-xna/

How do I go about making the raven class in the above player controlled? If I could control it myself, it would be a great help, but I don't know how to go about it.

# Answer
Change the raven's `hunt` method to hunt the mouse pointer instead of the nearest sparrow. Something like:

```
private void Hunt()
{
    offSet += mouse.Position - position;
}

```

This will have the raven hunting the mouse pointer, and therefore following the mouse instead of a sparrow. Wa-la, player controller raven.

Setting the ravens position directly to that of the mouse pointer will work, but you'll get a raven that can move across the screen very, very fast.

Keyboard control is a bit more complicated if you want more natural looking flight. A simpler way to do keyboard control would be to use the keyboard to position a target for the raven to fly towards, similar to the mouse control. But that's not very intuitive for the player. So instead I would do as JHocking suggests, use the arrow keys to increment the offset value:

```
if (left arrow) {
    offset.x = -1;
} else if (right arrow) {
    offset.x = 1;
} else {
    offset.x = 0;
}
if (up arrow) {
    offset.y = 1;
} else if (down arrow) {
    offset.y = -1;
} else {
    offset.y = 0;
}

```

That will probably give you some ugly flight, but it will give you a start. You should probably implement some better steering for your raven.
> 5 votes

---
Tags: xna, c#, xna-4.0, ai
---


title: XNA- Texturing problem, exporting model

text:
# Question
Title: XNA- Texturing problem, exporting model
How,can I disable coloring when texture is applied, because right now the texture is being colored over.

```
foreach (BasicEffect effect in mesh.Effects)
{
    effect.TextureEnabled = textureApplied;

    if(textureApplied)
        effect.Texture = Texture2D.FromStream(GraphicsDevice,System.IO.File.OpenRead(texturePath));
    else
    {
        effect.DiffuseColor = ti.DiffuseColor;
        effect.EmissiveColor = ti.EmissiveColor;
    }
    ...
}
mesh.Draw();

```

Also, is there any easy way for xna to export models? Or do I have to write my own?

# Answer
> 3 votes
First, set the DiffuseColor and EmissiveColor to Color.White when `textureApplied` is true. And please cache the result of `Texture2D.FromStream` and don't call it every frame!

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


title: Events Driven Library XNA C#

text:
# Question
Title: Events Driven Library XNA C#
Language: C# w/ XNA Framework

Relevant and hopefully helpful background info:

I am making a library using the XNA framework for games I make with XNA. The Library has a folder(Namespace) dedication to the GUI. The GUI Controls inherit a base class hooked with the appropriate Interfaces. After a control is made, the programmer can hook the control with a "Frame" or "Module" that will tell the controls when to update and draw with an event. To make a "Frame" or "Module", you would inherit a class with the details coded in. (Kind of how win forms does it.) My reason for doing this is to simplify the process of creating menus with intractable controls. The only way I could think of for making the events for all the controls to function without being class specific would be to typecast a control to an object and typecast it back. (As I have read, this can be terribly inefficient.)

Problem:

Unfortunately, after I have implemented interfaces into the base classes and changed

```
public delegate void ClickedHandler(BaseControl cntrl);

```

to

```
public delegate void ClickedHandler(Object cntrl, EventArgs e);

```

my game has decreased in performance. This performance could be how I am firing the events, as what happens is the one menu will start fine, but then slowly but surely will freeze up. Every other frame works just fine, I just think it has something to do with the events and... that is why I am asking about them.

Question:

Is there a better more industry way of dealing with GUI Libraries other than using and implementing Events?

Goal:

To create a reusable feature rich XNA Control Library implementing performance enhancing standards and so on.

# Answer
The lag was caused due to an update method in my base text control. I had a mistake of running a loop a ton of times when it did not need to be ran.

I have also remove all instances of EventArgs from the library as I personally see no point in them.

At this time, I have read quite a bit of posts saying events are appropriate for menus, but not necessarily for gameplay. The preferred way (That I have noticed.) is to use a state based form. So, really, you would check manually to see if something checks.
> 1 votes

# Answer
Wild stab in the dark:

You might have some events that fire very often (like every frame), for example OnMouseMove, and after your change of parameters you now create a new EventArgs at every call resulting in garbage piling up after a while. If I am correct then this should be more of an issue on x-box or windows phone than on PC.

A fix for this could be to not create EventArgs unless absolutely necessary for those calls that might happen very often but use value types instead. Or maybe use a circular buffer or something as an object pool for those eventargs.

I don't know how nuclex or the others do this, myself I have just avoided implementing calls that would occur too often.
> 0 votes

---
Tags: c#, xna, gui, events
---


# Question
Title: Rendering only a part of text FTGL, OpenGL
I'm using FTGL library to render text in my C++ project.

I can easily render text by using:

```
CFontManager::Instance().renderWrappedText(font, lineLength, position, text);

```

Unfortunately there is a situation in which this Button which displays text, is partly hidden because of resizing container in which it is situated. I'm able without any problem to draw Button's background to fit the container, but I've got a problem with doing the same with a text. Is it possible to somehow draw only text for given width and the rest just ignore?

This is a screen which presents my problem:

As you can see, the Button "Click here" is being drawn properly, but I can't do the same with "Click here" text.

# Answer
> 3 votes
Perhaps you could try scissor testing the window when drawing text?

```
glEnable(GL_SCISSOR_TEST);
glScissor(windowX, windowY, windowSizeX, windowSizeY);
CFontManager::Instance().renderWrappedText(font, lineLength, position, text);
glDisable(GL_SCISSOR_TEST);

```

You can also apply this to everything within the window as a single, unified solution.

---
Tags: c++, opengl, gui, fonts
---


# Question
Title: How can I achieve an "8-bit graphics" look?
I have a strong programming background just not from game development. I only made some pong and snake in high school and I did some OpenGL in college.

I want to make my own game engine. Nothing fancy just a simple 2D game engine. But because I'm kinda old school and feeling retro. I want graphics to look like old 8 bit games (megaman, contra, super mario, ...).

So how were the old games made back then? I want the simplest approach. Were they also using assets (images) like newer engines now do? How do you achieve this kind of rendering using OpenGL?

Keep in mind. Simplest solution. I want to know how it was made back then and how I can replicate that. Doesn't even have to be OpenGL. I can draw on window canvas. I do want to make it from scratch basically.

# Answer
> 7 votes
> So how were the old games made back then?

Completely differently -- more akin to what we would now call "embedded system programming". Mode-based graphics from 8-bit consoles and arcade boxes were driven by the hardware, not the software. The game code (typically assembly) poked specialized memory on an instruction-schedule (e.g. X instructions per scanline).

> How do you achieve this kind of rendering using OpenGL?

Texture-map a quad with filtering turned off. Better yet, batch several quads together and atlas the assets for better performance.

---
Tags: opengl, 2d, graphic-effects
---


# Question
Title: How to rotate a sprite using multi-touch with AndEngine?
I am new to Android game development. I am using AndEngine GLES-2. I have created a box with a sprite. This box is now draggable by using the code below. It works fine.

But I want multi-touch on this: I want to rotate the sprite with two fingers on that box, and to keep it draggable.

I've no idea how do do that, which way should I go?

```
final float centerX = (CAMERA_WIDTH - this.mBox.getWidth()) / 2;
final float centerY = (CAMERA_HEIGHT - this.mBox.getHeight()) / 2;

Box = new Sprite(centerX, centerY, this.mBox, this.getVertexBufferObjectManager()) {

    public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {

        this.setPosition(pSceneTouchEvent.getX() - this.getWidth()/ 2, pSceneTouchEvent.getY() - this.getHeight() / 2);

        float pValueX = pSceneTouchEvent.getX();
        float pValueY = CAMERA_HEIGHT-pSceneTouchEvent.getY();

        float  dx = pValueX -  gun.getX();
        float  dy = pValueY -  gun.getY();

        double  Radius = Math.atan2(dy,dx);
        double Angle = Radius * 360 ;

        Box.setRotation((float)Math.toDegrees(Angle));
        return true;
    }

```

# Answer
As far has I know the engine doesn't support it, but the multi-touch extension does support dragging of entities.

I think you could attach two invisible entities to your box, enable multitouch drag on them and try to adjust the angle of your box respectively with the x,y position of both of the boxes.

That's surely not the easiest solution, but I think it's feasible.
> 2 votes

---
Tags: android, andengine
---


# Question
Title: How do you access Target in a Beam ParticleSystem in UDK?
I have a Beam ParticleSystem which looks like this:

I want to set the Target location when the effect plays, but I can't figure out how to do that from UnrealScript.

I've looked at the UDN page on it: link

But this doesn't seem to explain how to access the relevant info from script. I am currently able to get the effect to play, but I just can't set the endpoint.

# Answer
Turned out to be quite simple:

```
function PlayTeleportBeamSystem(Actor SourceActor, ParticleSystem PSystem, Vector Target, optional Vector Source = Vect(0, 0, 0))
{
    local ParticleSystemComponent PSysComponent;

    PSysComponent = new(SourceActor) class'ParticleSystemComponent';
    PSysComponent.SetTemplate(PSystem);
    SourceActor.AttachComponent(PSysComponent);
    PSysComponent.ActivateSystem();
    if(!IsZero(Source))
    {
        PSysComponent.SetBeamSourcePoint(0, Source, 0);
        PSysComponent.SetBeamSourcePoint(1, Source, 1);
    }
    PSysComponent.SetBeamEndPoint(0, Target);
    PSysComponent.SetBeamEndPoint(1, Target);

    m_TargetedTeleportSystemComponentArray.AddItem(PSysComponent);
}

```
> 1 votes

---
Tags: udk
---


# Question
Title: How to make the game wait for an animation to finish?
I'm teaching myself andengine while trying to make a match-3 puzzle, so far I have a grid of gems that I populate and can move then around. Matching gems and new gems falling is working already. My problem is that the game keeps flowing while animations runs. How can I make the flow suspend until movement is done?

I use entity modifiers for the gems animations. `MoveYModifier` for the fall and `PathModifier` for the swap.

# Answer
You could override the entity modifier and execute some code at the beginning of the modification and on its end

```
MoveYModifier yourModifier = new MoveYModifier(3, 0, 10)
{
        @Override
        protected void onModifierStarted(IEntity pItem)
        {
                super.onModifierStarted(pItem);
                // Your action after starting modifier
        }

        @Override
        protected void onModifierFinished(IEntity pItem)
        {
                super.onModifierFinished(pItem);
                // Your action after finishing modifier
        }
};

yourEntity.registerEntityModifier(yourModifier);

```
> 3 votes

---
Tags: android, andengine
---


# Question
Title: How to calculate the inverse of a 4*4 opengl transform matrix
I am transforming my camera like any other object. I would like to set the view model matrix to the inverse of this so that I can draw the rest of the objects relative to the camera.

How do i calculate the inverse transformation?

*I construct this matrix from a quaternion and a position vector, if it is easier to find the inverse of these then feel free to post.*

# Answer
In order to invert a rotation by unit quaternion `q` followed by a translation `v`, you apply a rotation by unit quaternion `q'` followed by a translation `v'` where:

* `q'` = `~q` (conjugate of `q`, *ie.* inverse of rotation `q`)
* `v'` = `-~q v q` (transform of `-v` by the *inverse* of rotation `q`)

If you only do translations and rotations, it is simpler to not use transformation matrices until the final matrix is constructed.
> 5 votes

# Answer
Inverting a matrix is a complex task so I'd recommend snatching an implementation from some library. For instance, here's the matrix code from OpenTK, search for the `Invert` method and see how it was implemented.

https://opentk.svn.sourceforge.net/svnroot/opentk/trunk/Source/OpenTK/Math/Matrix4.cs

But if you're creating your matrix like:

```
RotationMatrix(quaternion) * TranslationMatrix(position)

```

It might be worth trying to do:

```
TranslationMatrix(-position) * RotationMatrix(conjugate(quaternion))

```

Not sure if it will work, but that's how I usually create a view matrix for 2D games, using an angle instead of a quaternion.

Related answer: https://gamedev.stackexchange.com/a/28833/11686
> 4 votes

# Answer
The inverse of a non-scaling rotation matrix is just its **transpose**.

If you construct a rotation matrix `R` from the quaternion, then the inverse of that rotation matrix (the "unrotation matrix" as it were) is just the transpose of `R`.

The reason this works is because rotation matrices are made up of orthogonal vectors.

How to handle the translation component depends on if you are translating before the rotation or after the rotation. In general to "untranslate" by an offset `v`, you just translate by `-v`.
> 0 votes

---
Tags: 3d, matrix
---


title: STL for games, yea or nay?

text:
# Question
Title: STL for games, yea or nay?
Every programming language has its standard library of containers, algorithms, and other helpful stuff. With languages like C#, Java, and Python, it's practically inconceivable to use the language *without* its standard lib.

Yet, on many C++ games I've worked on, we either didn't use the STL at all, used a tiny fraction of it, or used our own implementation. It's hard to tell if that was a sound decision for our games, or one simply made out of ignorance of the STL.

So... is the STL a good fit or not?

# Answer
Back when I worked in professional game development, STL was too immature and bloated. But that was \>10 years ago.

Now I work in military simulation, which has even tougher performance requirements (like the framerate can never go below some FPS). In military simulation STL is used all over the place.

Some of the people who tell you not to use STL use the argument that it's not always the perfect or even the best solution to the problem. But that isn't an answer to the question. The question should be: Is there something inherently wrong with using STL in games? I'd say no, STL is most of the time a better implementation than what a user would come up with on their own.

Just make sure you know how to use the STL, and use it in your game. Read some books and look at the implementation code in the STL you are using.
> 197 votes

# Answer
I would say that, off the top of my head, it is a better idea to use the STL unless you know *exactly* why you don't want to use it.

Here's the thing about the STL: it is developed by people who are smarter than you are. That's not intended to be offensive or anything, it's just that the STL is developed by people whose work is actually building the STL. It's going to be about as practically fast as the platform can allow and will generally be much more robust than a home-rolled solution (and this should be as much of a concern *if not more* than worrying about raw speed--because your game needs robustness a good bit more than you need speed; the latter is meaningless without the former).

The complaints that the STL enforces a "narrow view of the world" strike me as a little silly. They're containers. They have a limited set of operations because containers have limited sets of operations. What are you doing that doesn't jibe with this?
> 67 votes

# Answer
I've seen very few reasons not to use the STL for games.

For the memory allocation issues, many people don't know this but you can write custom allocators for your STL container classes. Allocators are basically policy classes you pass into your templates to determine how allocations are performed. Using these you can usually work around whatever memory issues are problematic on your platform of choice.

Of course, if you're using the STL and doing dumb things like maps of strings to large, non-pointer types, then you have bigger problems on your hand.
> 38 votes

# Answer
The default STL has a fair number of issues that make it difficult to use with games, especially when it comes to memory alignment.

A customized variant such as the EA STL is specially designed for games and can get you much better memory performance and console usability. It became open source in 2016, under a BSD-3 clause, with a repository on GitHub.
> 23 votes

# Answer
If you find yourself rewriting something that already exists in the STL, for any reason, **stop**. Use the STL.

The STL has been optimized over years of analysis and time, and it's a safe bet you're probably not going to write something that's more efficient. That's not to say you should use STL where a simpler solution may be possible (i.e. use an array when you have a known quantity of things, not a stl::list), but if you're writing your own implementation of a map (the basic data structure, not a game world map), you're doing it wrong.
> 20 votes

# Answer
Here is what Mike Acton (Engine Director at Insomniac Games of Spyro the Dragon, Ratchet & Clank and Resistance fame) had to say about this when asked here. Note he was asked about both STL and Boost in general as related to usage in game dev.

**STL/Boost, does it belong into gamedev? If only parts of it, which ones?**

> You're asking about two different things here, right? STL and Boost, separately. But really, my answer is the same: There's nothing *wrong* with either one per se, but I discourage their use. Use of either encourages people to *fit* a solution to a problem rather than *finding* a solution to a problem. The solution should always be appropriate for the data at hand and the constraints of the hardware, etc. Both STL and Boost have an extremely narrow view of the "world" and their appropriate use is limited. Really, I discourage them because they lead programmers down the wrong direction right away, I often say if you feel like you need either one you probably don't really understand the problem that you're trying to solve.

I have also noticed that most pro game developers strive more towards C than C++.
> 20 votes

# Answer
Is STL a good fit for games? Definitely. Games are complex pieces of software, the STL provides features that help manage complexity, so it's good.

Is it a good fit for your platform? Not necessarily. If you're writing for a console then you have to be very careful about memory and cache usage. The STL doesn't make this very easy.

I think that all too often we mistake "games" for "high performance real-time games that run on embedded or bespoke hardware", but it's important to make a distinction. If you're writing a Windows game that isn't trying to run in fullscreen at a constant 60fps then there's no reason to avoid the tools that the standard library gives you.
> 17 votes

# Answer
I know this is very late to the party, but time changes and answers stay around. C++11 has pretty sweeping changes, many of which are to increase the performance of C++ and the standard library. It seems those who do not use the STL or Boost, tend not to keep up with new standards either, leaving the home spun solutions lacking important improvements, of course this is not always the case.

I've used STL on every project from the mid 90s to today, with the exception of a short time at EA. I think the anti STL side had some marginally rational reasons to not use it. Those are largely gone. Custom allocators are one solution, using reserve is another, and not passing things by value is a third, but these are pretty simple and any programmer should know these. More importantly though is the use of algorithms. Compiler writers know exactly what a for\_each() does and can optimize the code. That cannot occur with a home rolled loop. for\_each() on a const object is even better. Microsoft optimizes for\_each in many ways including serializing. They also have the AMP library which has parallel\_for\_each(). If you get a chance, talk to compiler engineers about this. Console compilers are going to optimize what gets used, so it's a bit of a chicken and egg problem. Microsoft is going very heavy with C++11 and the next XBox will be no different. I have no idea about PS4, we haven't gotten one yet.

Custom allocators is one way to handle the memory issue, but another (often overlooked) option is to use class based new and delete. Huge performance increases can be had this way.

The notion that Boost and STL have a narrow view of solving problems is pure insanity. I'm stunned at how many things in the STL and Boost are customize-able through traits and policies. Look for case independent string compare as an example.

Regarding long link times and code bloat, the new *extern template* should help with this. Generally I find long compile times come from excess coupling and misuse of pch.

The most compelling reason to use STL over homespun is there are millions of people who can help you with the STL. As always, don't optimize prematurely and test, test, test.
> 12 votes

# Answer
This is a hot topic in game development. I personally don't recommend it, except perhaps for EASTL as mentioned above. I have two main problems with STL (technically "The C++ Standard Library", as STL is no longer the name) in games. 1) Dynamic memory allocation often wastes a lot of runtime in games when STL is used. 2) Use of STL encourages an array-of-structs approach to game architecture, whereas a struct-of-arrays approach is much more cache friendly.
> 9 votes

# Answer
It depends. How big is the project, what platform(s), and what is the timeline?

If you're working on a large project, on platforms with limited resources, with a significant timeline and budget, then you can save yourself a lot of trouble by avoiding the inevitable hell that will be looking at a half a million line code base that's littered with STL, can't keep a framerate above 30, eats enough RAM to fit several more assets, and takes 2 hours to build.

In other situations however, STL and even Boost can be very useful when applied appropriately. I've worked on titles that used a selection of STL/Boost, and were an absolute dream to code for: fewer bugs/leaks and easy to maintain code means more time coding fun new features! For hobby projects especially, that's a huge win in the motivation department.

Know when to trade performance for convenience!
> 5 votes

# Answer
IMHO I'd say it's a good fit since STL already works well and is optimized for the tasks it's made for. Besides, you're working on a game so, use the tools you have at hand that makes your life easier and your code less prone to bugs.

Why bother reinventing the wheel when you can be working on something else like the game's AI, user experience, or better yet; testing and debugging?
> 4 votes

# Answer
STL is absolutely fine for use in games, as long as you understand it well. Our engine makes pretty extensive use of it and it hasn't ever been an issue. I don't have any experience with console development, which may be an entirely different story, but it is well supported on all of the PC platforms (Windows/Mac/Linux).

The most important thing is to understand what the strengths and weaknesses of each container type are and pick the correct container for the job you are doing.
> 4 votes

# Answer
My former employer shifted from using a robust set of custom container classes to STL. Build times went up and ease of debugging went down, both pretty significantly. If we'd been starting from scratch, STL (perhaps better used) would likely have made sense, but it was never clear to me that we gained anything in switching to STL that would justify throwing out working, fast, debuggable code.

For my personal projects, whether STL fits or not depends on the project. If I'm trying to do some Mike Acton-style data-driven, memory-and-cache-access optimized work, I'll at least think about rolling my own custom data structures. If I'm prototyping some algorithms or gameplay and don't care about performance, scalability, target platform, etc. I'll automatically grab STL.
> 4 votes

# Answer
My 2 cents on this is that the STL works just fine. I've been developing a 3D game engine (not AAA quality, but advanced enough - scripted entity types, deferred renderer, integrated Bullet physics) for PC and I have yet to see containers become the main bottleneck. Incorrect 3D API usage and poor algorithms have been the best targets (determined by profiling!) every time I've gone in and tried to eek out a bit more performance.
> 4 votes

# Answer
I've built games using STL and I like it, and it seems to perform well.
> 3 votes

# Answer
Good question! A more specific question is what are some common requirements that a game would have that cannot be met with STL and Boost.

In my experience, the tight memory limitations of console hardware make any kind of dynamic sized container a bad idea regardless of how clever your custom allocator is. Containers that have no deliberate bounds encourage programmers to write code that does not constrain the bounds of their data sets. Depending on countless variables that are difficult to track you may exceed your memory limitations. I have a hunch that this is one of the primary causes of instability in modern games.

Additionally, overuse of templates can lead to very long compile times in a large code base, and will bloat the size of your executable so that it would no longer fit within the cache of, say, an auxiliary core on a ps3.

However, for PC-only development I think STL and Boost are very good. While general-case solutions are not always ideal, they are often good enough. Your first solution to a problem is almost never ideal, and you improve or replace the inadequacies until it is good enough.
> 3 votes

# Answer
The STL is a good fit for your game if the STL is a good fit for your game.

As with all technology choices made during development, you need to weigh up the pros and cons -- will rolling my own library give me more beneficial memory usage, performance, and productivity than simply using the STL? Possibly; though it's just as easy to create a `vector` implementation that uses more memory, is slower, and requires large amounts of maintenance to remain function compared to what already exists.

People should not avoid using the STL in their games because other people avoid using the STL in games; they should avoid using it if they've weighed up all of their options and they *genuinely believe* that another implementation will improve the quality of their product.
> 2 votes

# Answer
As with most questions the answer is never "yea or nay", black or white. STL is a good fit for some problems, using it for those problems should be fine. It's a mistake to assume it's useless, yet it's also a mistake to assume that it is appropriate to use in every situation.

The biggest issue to watch out for when using STL in game development is memory allocation. STL's default allocators don't seem to fit well into preferred allocation strategies for game development. Of course custom allocators can be used, but this makes the whole idea less appealing if you're considering whether to add STL to a non-STL codebase.

Add to this that if your codebase is non-STL, you may not have anyone familiar enough with STL or template concepts to implement the custom allocators correctly.
> 2 votes

# Answer
I think this discussion can be summarized as follows:

mediocrely written application-specfic code \< well-written general purpose code \< well-written application-specific code

Anyone whose home-grown solution would fall into category 3 surely knows the answer to the original question for their particular problem. The STL falls into category 2. So for someone who needs to ask the question, "should *I* use the STL", the answer is probably yes.
> 2 votes

# Answer
STL is all right for use on a PC, because its advanced virtual memory system renders the need for careful memory allocation a bit less crucial (although one must still be very careful). On a console, with limited or no virtual memory facilities and exorbitant cache miss costs, you’re probably bett er off writing custom data structures that have predictable and/or limited memory allocation patt erns. (And you certainly won’t go far wrong doing the same on a PC game project either.)
> 2 votes

# Answer
I think this question is really a larger unasked question -- should I use **X** in my **Y**? And the only way to really answer that is to try it for yourself. For every person you find that says that X works great, you'll find someone who says it's horrible. And both of them are right -- for their project.

The great thing about software, unlike most other disciplines, is that you can always change things later on if you find it's not working the way you would like it. You find out later that STL isn't working for you in this project? Rip it out, put something else in it's place. Don't like how you divided the duties among your objects? Refactor. Don't like that you used objects? Replace them with straight C methods. Don't like everything being stored in structs and methods to manipulate them? Replace them with C++ objects.
> 1 votes

# Answer
I say nay to the STL. My reason is quite simple:

1. You dont' need the STL to write games. Not even large ones.
2. STL dramatically increases your compile time.
3. Large compile time leads to less iterations over your development.

I hold iteration count to be of the highest importance, so I just stay away from the STL, and any other development technique that slows down iterations (like architecting for the sake of it, or script languages that need to be compiled).

Costly iterations lead to huge development teams of people trying to get stuff done with very little actually happening. I've seen it and heard it, and one of the culprits seems to be compile times for template libraries.
> 1 votes

---
Tags: c++
---


title: Unity Occlusion Portals: What and How?

text:
# Question
Title: Unity Occlusion Portals: What and How?
(Here I eat my words on Meta about posting Unity questions on Unity Answers... since that site is less responsive than this one.)

Unity provides cell-based Occlusion Culling (via Umbra, I believe). However, a newer feature that it supports is Occlusion Portals.

The question is, if BSP-based occlusion culling is already a feature of Unity, what do portals add, and how?

PS. This question is not "What are portals?" -- I'm aware of the original Quake BSP-style portals -- which is partly why I find the explicit portal concept in Unity odd, since it uses BSP anyway.

# Answer
As far as I understand, portal culling is one of many culling techniques.

That being said, we can infer that Unity could pre-compute potentially visible sets (PVSs) in many complementary ways: computing what's inside the frustum (visibility culling), hierarchically subdividing space and querying it (traditional occlusion culling), dividing the space in rooms and discarding objects that are in a room disconnected from the viewer's room (part of portal culling), etc.

So, what would portal culling add to BSP-based occlusion culling?

PVSs could be determined faster.

Also, saying that you can open/close portals in runtime means you'll recompute your PVS dynamically so that maybe you can determine visibility more accurately.
> 3 votes

# Answer
I believe this is explained in detail in the Umbra 3 article here.
> 1 votes

---
Tags: 3d, algorithm, unity, occlusion
---


# Question
Title: Move projectile in direction the gun is facing
> **Possible Duplicate:**
> Move sprite in the direction it is facing?

I am attempting to have a projectile follow the direction a gun is facing. When using the following code I am unable to make the projectile go in the right direction.

```
float speed = .5f;

float dX = (float) -Math.cos(Math.toRadians(degree)) * speed;
float dY = (float) Math.sin(Math.toRadians(degree)) * speed;

```

Can anyone tell me what I am doing wrong? The degree is the direction the gun is facing in degree's.

# Answer
Given the behavior you were experiencing and the results of my suggestion in the comments, the problem is that you need to apply the unary `-` to the result of `Math.sin` instead of `Math.cos`.

This is probably a result of the correspondence you have between positive/negative rotation and clockwise/counterclockwise direction.
> 0 votes

---
Tags: java, mathematics, physics, graphics
---


title: How to transform mesh components?

text:
# Question
Title: How to transform mesh components?
I am attempting to transform the components of a mesh directly using a 4x4 matrix. This is working for the vertex positions, but it is not working for the normals (and probably not the tangents either).

Here is what I have:

```
// Transform vertex positions - Works like a charm!
vertices = mesh.vertices;
for (int i = 0; i < vertices.Length; ++i)
    vertices[i] = transform.MultiplyPoint(vertices[i]);

// Does not work, lighting is messed up on mesh
normals = mesh.normals;
for (int i = 0; i < normals.Length; ++i)
    normals[i] = transform.MultiplyVector(normals[i]).normalized;

// Tangents?? I really do not understand these guys
tangents = mesh.tangents;
for (int i = 0; i < tangents.Length; ++i) {
    Vector4 temp = transform.MultiplyVector(tangents[i]).normalized;
    temp.w = tangents[i].w;
    tangents[i] = temp;
}

```

Note: The input matrix converts from local to world space and is needed to combine multiple meshes together.

# Answer
> 3 votes
If your normal matrix does not have uniform scale (ie same amount of scale in x,y,z directions), then it will screw up the normals.

Try creating a second matrix `normalMatrix = transform.inverse().transpose()` and see if that solves your problem. A tangent is just a vector that "grazes" the surface.

---
Tags: mathematics, unity, matrix, transformation
---


title: Longest distance Kinect can take

text:
# Question
Title: Longest distance Kinect can take
I am planning a project using Kinect's depth sensoring but I do not have a Kinect yet.

Newest information from Microsoft's website says it can take **over 4m**, and Wikipedia page says **over 6m**. What I want is **about 20m**, is that OK for Kinect? If not what is the bottleneck, SDK or hardware?

# Answer
Error will increase dramatically as you go farther out. At 20m, I don't think you'd get anywhere near the quality you need to run any kind of application reliably. Keep in mind that the resolution of the camera is only 640×480 pixels. Things farther away are smaller, and harder to discern. It's a hardware limitation. You will likely find it very difficult to use if you're expecting results at 20 meters.

See this blog post for more information about the limitations.
> 5 votes

---
Tags: kinect
---


# Question
Title: Is there any way to enable the HiDef graphics profile property on a Silverlight 5 3d Web App?
I have an XNA Windows Game that uses the HiDef profile to load complex fbx and obj files. Trying to move it over to a Silverlight 3d Web App, Silverlight seems to only want to use the Reach profile, and I get an error that the Reach profile does not support a sufficient number of primitive draws per call. Is there any way to change to HiDef in Silverlight 5? It is not in the project properties and attempting to change it in mainpage.xaml.cs only gives me the option of setting it to Reach.

# Answer
Unfortunatelly no, HiDef profile is only available on Windows PC and Xbox 360. You can assume `Silverlight 5 == Windows Phone` for the table referenced. See also.
> 3 votes

---
Tags: xna, silverlight
---


# Question
Title: Admob banner not getting remove from superview
I am developing one 2d game using cocos2d framework, in this game i am using admob for advertising, in some classes not in all classes but admob banner is visible in every class and after some time game getting crash also.

I am not getting how admob banner is comes in every class in fact i have not declare in Rootviewcontroller class. can any one suggest me how to integrate Admob in cocos2d game, i want Admob banner in particular classes not in every class, I am using latest google admob sdk, my code is below:

Thanks in advance

\`

```
-(void)AdMob{
NSLog(@"ADMOB");

CGSize winSize = [[CCDirector sharedDirector]winSize];
// Create a view of the standard size at the bottom of the screen.

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){

    bannerView_ = [[GADBannerView alloc]
                  initWithFrame:CGRectMake(size.width/2-364,
                                           size.height -
                                           GAD_SIZE_728x90.height,
                                           GAD_SIZE_728x90.width,
                                           GAD_SIZE_728x90.height)];

}
else { // It's an iPhone

    bannerView_ = [[GADBannerView alloc]
                  initWithFrame:CGRectMake(size.width/2-160,
                                           size.height -
                                           GAD_SIZE_320x50.height,
                                           GAD_SIZE_320x50.width,
                                           GAD_SIZE_320x50.height)];
}

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
    bannerView_.adUnitID =@"a15062384653c9e";
}
else {
    bannerView_.adUnitID =@"a15062392a0aa0a";
}

bannerView_.rootViewController = self;
[[[CCDirector sharedDirector]openGLView]addSubview:bannerView_];
[bannerView_ loadRequest:[GADRequest request]];

GADRequest *request = [[GADRequest alloc] init];
request.testing =  [NSArray arrayWithObjects:
                  GAD_SIMULATOR_ID, nil];                              // Simulator

[bannerView_ loadRequest:request];
 }

   //best practice for removing the barnnerView_

-(void)removeSubviews{
 NSArray* subviews = [[CCDirector sharedDirector]openGLView].subviews;
 for (id SUB in subviews){
    [(UIView*)SUB removeFromSuperview];
    [SUB release];
 }
 NSLog(@"remove from view");
  }

    //this makes the refreshTimer count
-(void)targetMethod:(NSTimer *)theTimer{

//INCREASE OF THE TIMER AND SECONDS
elapsedTime++;
seconds++;

//INCREASE OF THE MINUTOS EACH 60 SECONDS
if (seconds>=60) {
    seconds=0; minutes++;
    [self removeSubviews];
    [self AdMob];
  }
NSLog(@"TIME: %02d:%02d", minutes, seconds);
 }

```

\`

# Answer
> 1 votes
Try adding it to the view with:

```
[[[UIApplication sharedApplication].keyWindow rootViewController].view addSubview:bannerView_];

```

And removing it:

```
[bannerView_ removeFromSuperview];

```

---
Tags: cocos2d-iphone, ios, objective-c
---


title: Fastest approach to 3D animation

text:
# Question
Title: Fastest approach to 3D animation
I'm currently tasked with designing a small HTML5 game. Having done everything by myself so far (3D models, codebase, game design, etc) I'm now at a point where I'm running out of time.

I've less than a day to animate and bind everything together. However, that's exactly my problem.

I was under the naive impression that everything would be easier if I went with pre-rendered 3D models. However, I didn't consider the most difficult part. Animation.

After having spent over an hour trying to figure out messiahStudio, I figured it's time to ask for outside help.

Is there any easier solution to 3D animation than 3D rigging? What I'm basically looking for is some sort of tool that allows me to simply grab and move/deform select polygons.

It doesn't have to be as life-like and accurate as rigging, just efficient enough.

Were the circumstances any different, I might just learn how to rig. But that's sorely out of scope right now.

PS:The models were created in Sculptris but are fairly low-poly.

# Answer
Rigging will save you time in the long run. You don't have to get fancy with constraints or IK chains. Just slap in a basic skeleton and let the automatic weighting do its job. Any later adjustments can be done a lot easier if you've used a rig, and animations on rigs can be transferred between characters if you reuse the same skeleton.

The other option is to use what is called morph target animation, per-vertex animation, shape interpolation, or blend shapes. Deform the mesh for each key frame using sculpting tools or otherwise just pulling the model around. It depends on what your toolset can do, whether this is an actual possibility. It's normally used for facial expressions and similar subtle animations that are difficult to do with rigs.
> 2 votes

# Answer
Thanks guys.

I tried vertex animation inside several tools, but have decided that rigging is probably the way to go after all.

Right now I'm trying to rig my model with anim8or. Unfortunately, I don't really know how to split my model into several parts (which is how they did in in the Anim8or tutorial).

I guess I'll have to find another rigging tool which is a bit more straight forward than messiahStudio but also more flexible than anim8or.
> -1 votes

---
Tags: rigging
---


title: Ray casting on a mesh using libgdx

text:
# Question
Title: Ray casting on a mesh using libgdx
I'm trying to perform ray casting on a mesh using libgdx.

I found this code sample and it misses some explanations. What do these vectors stand for? What is `globalIntersection` and `localIntersection`?

# Answer
* globalIntersection is the nearest intersection to the origin of the ray.
* localIntersection is the intersection of a mesh with the ray.

The simplified algorithm is:

```
iterating on the meshes:
    find the intersection of current mesh with ray (localIntersection)
    if intersection is near that globalIntersection:
        update globalIntersection with localIntersection

```
> 1 votes

---
Tags: software-engineering, libgdx, raycasting
---


# Question
Title: Game Asset Storage: Archive vs Individual files
As I am in the process of creating a 3D c++ game and I was wondering what would be more beneficial when dealing with game assets with regards to storage. I have seen some games have a single asset file compressed with everything in it and other with lots of little compressed files.

If I had lots of individual files I would not need to load a large file at once and use up memory but the code would have to go about file seeking when the level loads to find all the correct files needed.

There is no file seeking needed when dealing with one large file, but again, what about all the assets not currently needed that would get loaded with the one file?

I could also have an asset file for each level, but then how do I deal with shared assets

This has been bothering me for a while so tell me what other advantages and disadvantages are there to either way of doing things.

# Answer
> 10 votes
From both performance and storage points single resource file is more beneficial solution (however in practice it's not always really noticeable). The drawback is that it's harder to update and manage.

IMO it's not that important usually, just use that is more convenient for you, it's really just a technical detail that should not be considered until you really notice some problems with it.

# Answer
> 4 votes
Unpacked files make it easier for the user to edit and replace files, making the game much more modding-friendly. This can be seen as an advantage or disadvantage, depending on your attitude towards modding.

**From a performance-perspective:** Loading a lot of small files from the hard drive can be a lot slower than a single, large one, because the defragmentation of a filesystem will usually try to avoid splitting large files, but a lot of small files in the same directory can be scattered all over the disk. So when you load thousands of small files, the drive might have to do a lot of seeking. But on the other hand, using archives might make it more costly to get individual files from inside the archives (depending on how your archives are structured internally), so you should try to group files which are usually needed together.

**From a maintainance perspective:** Unless you have a tool to do incremental updates to your packet files, your patches will get a lot larger when you have to replace whole packages to patch an individual file.

# Answer
> 1 votes
Typically a package would be faster, however it is not always as convenient, as Petr said. One way to combat that however is to make your engine able to load loose files and pack files. Then, in debug mode, load loose files, and in release mode, load from a pack

---
Tags: c++, software-engineering, assets, asset-management
---


title: New to creating AI - where to start?

text:
# Question
Title: New to creating AI - where to start?
I am new to game programming and am trying to make a basic 2d top-down space game with 2 space ships that fight each other. I am doing well with the user controlled space ship, but have no idea how to even start programming an AI. Are certain methods/patterns better for this situation? Where would I even begin?

# Answer
> 34 votes
The **Strategy pattern** is great for determining what to do but not when to do it. You're also going to need to use **Finite State Machines** to know which state your AI is in and what appropriate decisions are available.

**A Practical Guide to Building a Complete Game AI: Volume I**

# Answer
> 28 votes
If this is your first time developing AI, you don't have to worry about things like the state pattern, behavioural maths or even get a book on the subject.

You can literally get away with something like this:

```
if( targetInRange == true )
{
    FireAtTarget();
}
else if( bulletComingTowardsMe == true )
{
    MoveAwayFromBullet();
}
else
{
    WanderAroundAimlessly();
}

```

The main aspect of getting AI correct is by thinking about what behaviours you want the character to have and how this can be achieved realistically. So for a basic spaceship enemy, I'd imagine the possible actions it could carry out would be to:

* Move around
* Fire
* Run away

And when could these actions happen?

* Move around - Nothing else to do
* Fire - When I spot an enemy
* Run away - When I'm low on health/When I'm taking fire/etc

After you have done this due to the low number of "states" that your character can be in, you can use a simple if statement like the one above. I would then recommend you look at Steering Behaviours as these are very simple behaviours to implement and can result in really good looking movement.

More can be found here: http://www.red3d.com/cwr/steer/
And I would definitely recommend Mat Buckland's book *Programming Game AI By Example*, especially when you're starting out.

When you are really comfortable with these, I would suggest looking at the State and Strategy Patterns.

The point is to start out small and simple. Don't worry about all these terms that everyone keeps flinging around about FSMs and design patterns and whatever. Design and build first of all, then worry about how you can improve it by using existing methods or standards.

Hope that helps!

# Answer
> 9 votes
You might want to look at the Strategy design pattern. Essentially write up same basic strategies of how the ships will behave:

* Move closer to target
* Attack target
* Run away from target
* Move towards power ups
* Use power ups

Then you will use logic (state machines) to choose between these strategies. For example: If the ships shields have fallen below 50%, then run away from the target and move toward power ups/healing items and so forth.

# Answer
> 9 votes
You might want to look at OpenSteer, and the Steering Behaviors documentation that goes with it. The source code is not beginner-level, but the concepts behind it should give you some good ideas.

# Answer
> 7 votes
May I suggest that you buy the book Artificial Intelligence for Games by Ian Millington - it's excellent! :) http://www.ai4g.com/

The source code is at Github - MIT license.

Of course, if you're not using C/C++, then this might be less relevant.

But really an awesome introduction to the world of Artificial stupidity/intelligence.

Things you're going to need from it are steering and state machines. For starters.

# Answer
> 2 votes
Some practical advice if you go for state machines: beware the megastate.

It's tempting to have a "flee" state which handles setting a position to flee to, setting a high target speed, clearing all targets, etc. It's much better to instead have many state machines, each handling one or few ship controls - eg a state machine that handles selecting a target position, one that handles guns, etc.

This may seem stupid, as you'd have to add flee states to each individual machine, but since you're constrained to only one or two outputs, your states end up very small so this should not be a problem.

Also, since each control is now under individual control, you can end up selecting a flee target position while still having the attack state control your guns. You can strafe an enemy while still conserving engine power because of a coolant leak. You can steer to avoid a collision while still dumping countermeasures. All these would be impossible with a single all-encompassing state machine.

# Answer
> 2 votes
Behavioral Mathematics for Game AI

Adding this book to the list of starting points for learning AI programming. With its focus on observation and behavior implementation rather than algorithms of limited application, I believe it is well suited to the task.

# Answer
> 1 votes
How to create AI is a tricky question, because it consists of many parts:

* You choose a general architecture/paradigm for your AI. Is it based on scripts? Will it use planning? Is it a simple FSM or do you prefer BTs?
* Then, you apply these paradigms with a specific implementation/set of tools.
* Now, you're left with game-design choices, as you have to think of behaviors that your architecture will use.

Other posters suggested great books and I'm fond of AI4Games suggested by jacmoe, even though it's quite general in parts (like a lot of books, which is of course understandable).

Of course, each type of game has its specific needs, and arcade/shooter games don't need complex architectures to support interesting gameplay. Simple steering libs will do the job as the basis of that behavior, and then you add details for various types of enemies (some, shoot periodically, some shoot by predicting the player's movement, some turn in order to face the enemy, others may coordinate their attacks etc).

* I think the best way to learn about game (AI) coding is too look at good, running code. So, explore ohloh.net and github and look for existing FOSS projects!
* Of course, you can choose **the** hard part and play an existing (but simple) game. Try to reverse engineer the behavior and think "How would I design this?". Of course, hints always help, and that's probably why you asked here at gamedev.SE!
* Something in-between is too look at existing shooter games within the GameMaker forums! You can find a lot of simple scripts that will do the trick! ;)

# Answer
> 1 votes
Think about what you do when you play the game. Ask yourself some questions.

* What information do I *need* to be able to make a decision?
* When do I react to changes?
* What are my "long term" goals in this particular play session?

Then, what I do is have the AI look at the play field and make a list of possible actions or movements that the AI could make based on those questions. I rank and sort these moves with a "smartness factor". Then, it's as simple as picking and executing a movement/action based on some combination of randomness and whatever difficulty level the player chose at the beginning of the game.

Then, after 500 milliseconds, I do it again.

It doesn't have any learning abilities or anything but with enough tweaking it can be pretty convincing, which it all that really matters

---
Tags: 2d, software-engineering, ai
---


# Question
Title: What is involved with writing a lobby server?
So I'm writing a Chess matchmaking system based on a Lobby view with gaming rooms, general chat etc. So far I have a working prototype but I have big doubts regarding some things I did with the server. Writing a gaming lobby server is a new programming experience to me and so I don't have a clear nor precise programming model for it. I also couldn't find a paper that describes how it should work. I ordered "Java Network Programming 3rd edition" from Amazon and still waiting for shipment, hopefully I'll find some useful examples/information in this book.

Meanwhile, I'd like to gather your opinions and see how you would handle some things so I can learn how to write a server correctly. Here are a few questions off the top of my head: (may be more will come)

First, let's define what a server does. It's primary functionality is to hold TCP connections with clients, listen to the events they generate and dispatch them to the other players. But is there more to it than that?

Should I use one thread per client? If so, 300 clients = 300 threads. Isn't that too much? What hardware is needed to support that? And how much bandwidth does a lobby consume then approx?

What kind of data structure should be used to hold the clients' sockets? How do you protect it from concurrent modification (eg. a player enters or exists the lobby) when iterating through it to dispatch an event without hurting throughput? Is ConcurrentHashMap the correct answer here, or are there some techniques I should know?

When a user enters the lobby, what mechanism would you use to transfer the state of the lobby to him? And while this is happening, where do the other events bubble up?

# Answer
Model everything as objects. You have the classes chat-room, game-session, player... Don't spawn new threads for new players. Instead try to see every class as a state machine: A player can be connected or disconnected, he has a TcpConnection and a variable specifying how much time he has left to make his move (just as an example).

Then when you have all your objects in an array or something like that, you iterate over it every 10milliseconds (the number is an example too ofcourse) and take appropriate actions.

For example, terminate a game-session if one of the players left the game, send moves from one player to the other player...

For all events that happen in the game you will have to send message trough the network. Create one extra class / enumeration that holds the different message types. If one player makes a move you could send this to the server "move d4 to d5" or something. If you only make a chess game, you can send strings trough the network. For anything more complex I would suggest you send only single bytes.

Typically game packets consist of: the length of the packet, the packet message type / event type (move, player-joined, player-left, ...) and the content (if a player joins, the content would be the name for example)
> 3 votes

# Answer
To limit the amount of needed threads you should have a look at Java NIO: http://en.wikipedia.org/wiki/New\_I/O
> 0 votes

---
Tags: java, server
---


title: Rotate/Translate object in local space

text:
# Question
Title: Rotate/Translate object in local space
I am just trying to create a movementcontroller class for game entities. These class should transform the entity affected by the mouse and keyboard input. I am able to calculate the changed rotation and the new globalPosition. Then I multiply:

```
 newGlobalMatrix = changedRotationMatrix * oldGlobalMatrix;
 newGlobalMatrix = MatrixSetPosition(newPosition);

```

The problem is that the object rotates around the global axis and not around the local axis.

I use XNAMath for the matrix calculation.

# Answer
> 1 votes
What you describe sounds like you are applying your local rotation after the global transformation has already been applied.

You need to apply the local transformation first - try flipping the order of multiplication of your matrices.

---
Tags: mathematics, rotation, movement, transformation
---