# Question
Title: Do I need to create my own or use a commercial server for the features and matchmaking options I want my game to support?
So I'm developing an indie turn-based game for iOS and, in coding up a Game Center matchmaking class, I'm starting to question whether Game Center is even the best choice for what I want this game to do. I need to figure out whether I need to create my own server, invest in a preexisting client or server service, or if I even need to use a server at all. If I do need to use a ready-made service other than Game Center, which server would accomodate my game's needs best? I have limited resources and funds. Here is the list of features I want my game to support, ideally:

1. Turn-based gameplay (a la "with Friends" and "with Buddies" games)
2. Smart matchmaking (matching users up with other players of comparable skill/achievements)
3. Random matchmaking
4. Facebook matchmaking
5. Specific username matchmaking
6. Contact list matchmaking
7. A way to select what "type" of match you want to challenge an opponent to. (In random, smart, and Facebook matchmaking, there will be different "wagers" the player can make. \[e.g. "I wanna play a random opponent for 1000 points. Now, I wanna play my Facebook buddy for 1,000,000 points."\] There will be a predetermined range of amounts you can play for. It won't be customizable.)
8. Buddies list capability (Game-buddies, as opposed to contacts and Facebook)
9. A higher concurrent game cap than Game Center offers (which I still can't really find a straight answer on)
10. Scalability (it should support 2 or 20,000,000 players)
11. Objective-C compatibility
12. Flexibility (for all the stuff I haven't thought of yet)

Am I dreaming, here? Is there even a service that can handle all of these features? Do I need to invest months in learning a networking language to build my own? If so, how much would I need to spend on hardware?

I've been looking around all morning and, so far, the only seemingly viable option is SmartFox. Under "Everything and the kitchen sink" section here, it says they support "virtual world with Zones, Rooms and RoomGroups, create complex game challenges, send invitations, manage buddy lists, create custom permission profiles, oversee the security aspects and tons more."

http://www.smartfoxserver.com/overview/platform

Is there an option that Im just overlooking? Thanks for any help anyone can provide. Sorry for the long poast.

One last question: Does anyone know which server Dice with Buddies uses? I was experimenting with how many concurrent games I could get going and my ADHD kicked in at about 80 games. 80 concurrent games would be great for my game, but again, I need the other features I mentioned too. Thanks again.

# Answer
You need two things:

1. Some software to run on your server(s).
2. A hosting company to handle your server(s). AWS should be a decent option here, but it's not the only one. I wouldn't suggest buying your own hardware.

For turn based games the server workload should be relatively low, and an in progress game should not consist of anything more than a few extra entries in some database tables. Real time games need much more from the server as each player will send and receive several updates per second from the server.

Here's some more options for the software side of things:

Both are free for light usage.
> 0 votes

---
Tags: server, client-server, turn-based, matchmaking
---


# Question
Title: Would like some help in understanding rendering geometry vs textures
So I was just pondering whether it is more taxing on the GPU to render geometry or a texture. What I'm trying to see is whether there is a huge difference in rendering two scenes with the same setup:

Scene 1: Example Object: A dirt road (nothing else) Geometry: Detailed road, with all the bumps, cracks and so forth done in the mesh

Scene 2: Example Object: A dirt road (nothing else) Geometry: A simple mesh, in a form of a road, but in this case maps and textures are simulating cracks, bumps, etc...

So of these two, which one is likely to tax the hardware more? Or is it not a like for like comparison?

What would be the best way of doing something like this? Go heavy on the textures? Or have a blend of both?

# Answer
Scene 2 is cheaper. That's why bump mapping, normal mapping, parallax mapping, relief mapping etc where invented in the first place. You would need huge amount of vertices in order to reach the same amount of detail. Note however that with the advent of hardware tessellation, that too has become possible recently, though you still don't have the hugely detailed base mesh but generate that procedurally, e.g. through textures.
> 5 votes

# Answer
This works because texture mapping is a form of both precalculation and compression. The idea is that rather than having to store and continually recalculate all of the info needed to derive the end result per-vertex at a very fine level of tessellation, you instead encode it into a texture map (and at the most basic level, if you think about it, that's all that a texture map actually is) and do a fast lookup.
> 6 votes

# Answer
I think it strongly depends on the scene rendered and shaders used. It's usualy better to use low-poly geometry and add as much detail as possible via textures and pixel shader operations. But you have to have two things on your mind:

1. GPU have to process all the source geometry (at least to the point where the position in view-space is determined, then some culling optimizations can be done and geometry that won't be visible is omitted from further rendering) - if you do not generate geometry on GPU (using geomery shaders or tessellation shaders) this optimizations can be very significant, but if the source geometry is huge, this could be the bottleneck.
2. Per-pixel operations depend on the render target resolution, if we assume each pixel to be written only once. BUT this is usualy not true, due to pixel rewrites caused by rendering geometry, that is closer to camera, than scene rendered sofar (depth-test). This per-pixel performace is often called pixel-fill rate and could be bottleneck as well.

For example: Particle engines are usualy limited on the vertex count side and GPU raytracing apps are limited by pixel shader operations.

Hope this could give some insight to somebody. :D
> 3 votes

# Answer
GPUs incur a large amount of overhead when triangles are too small on-screen. There are two main reasons:

* There are fixed costs per triangle, associated with setting it up to be rasterized and pixel-shaded. For example, each triangle must be clipped to the viewport, edge equations for rasterization must be calculated, and plane equations for attribute interpolation must be calculated. It is possible for this to become a bottleneck if there are very many triangles.
* GPUs shade many pixels in parallel. Current GPUs work on groups of 32-64 pixels, and most likely they must all come from the same triangle - i.e. pixels from different triangles can't currently be merged together into one work-group. Therefore, triangles smaller than this waste some hardware resources that could otherwise be doing useful work.

See this article for some more details (the rest of that series also a must-read if you wish to understand how GPUs work).

The takeaway is that very highly tessellated meshes, with each triangle covering only a few pixels, are likely to be very slow to draw and do not use the GPU's hardware efficiently. Therefore, assuming that you want to render an image that contains pixel-level detail, the better way is to use a texture.

Texture samples are a lot of work too. However, there are some compensations:

* Mipmapping and the texture cache help you a lot by amortizing the slowest part: fetching the texel data from memory and decompressing it. Usually, nearby pixels will sample nearby parts of the texture, so your cache hit ratio is going to be high.
* The texture sampling hardware is designed to have many, many requests in flight at once. Texture samples can still be a bottleneck, but it's harder to bottleneck this than the triangle setup unit.
* When all of the pixels in a GPU work-group are waiting for texture samples, the GPU can suspend that work-group (like a thread sleeping) and do something else with that hardware until the texture samples come back.
> 3 votes

---
Tags: 3d, textures, geometry, hardware
---


# Question
Title: What could cause a sudden stop in Box2D?
I'm using Box2d for a game, and I have a bug that's driving me nuts. I've simplified the situation down to a square player sliding back and forth frictionlessly on top of a floor composed of a series of square tiles, driven by the left and right keys (which apply a horizontal force). Works great, sliding back and forth across the whole floor.

Except... Every once in a while, the player will suddenly stick at the edge of one of the tiles as if it is hitting a (nonexistent) wall. Further pushes in the same direction it was traveling will fail, but as soon as I push backwards once in the opposite direction, I can push forwards past the sticking point again. The sticking point seems to be random, except for being on the edge of a tile. Happens while going left or right.

For debugging purposes, I keep the Positions/velocity values for the previous two update ticks and print them out when this stop occurs. As an example, here you see the player moving right, decelerating slightly; pos2 should be about 8.7, but it stops dead instead.

```
tick0:  pos= 8.4636 vel= 7.1875
tick1:  pos= 8.5816 vel= 7.0833
tick2:  pos= 8.5816 vel= 0.0000

```

So, as the player is 0.8 and the tiles 1.0 wide, the player is stopping just as it is about to cross onto the next tile (8.5816 + 0.8/2 = 8.9816). In fact, I get a collision message (which I ignore except noting that it happened). It only seems to happen at x.5816 (or -x.4184) while moving right, and x.4167 (or -x.5833) while moving left

I said that it's like hitting a wall, but in fact, when it hits a wall, the numbers look more like:

```
 tick0:  pos0= 12.4131 vel2= 8.4375
 tick1:  pos1= 12.5555 vel1= 8.5417
 tick2:  pos2= 12.5850 vel0= 0.0000

```

so it moves further right on the last tick, which puts it in contact with the wall.

Anyone seen anything like this. Any suggestion on how I could be causing this behavior.

# Answer
> 3 votes
This is a common issue with Box2D and tile maps. The problem you're facing is referred to as "ghost collisions" and is addressed in the manual.

The simplest solution, in my experience, is to use edge shapes.

Basically instead of making the tiles Box2D boxes, make the tiles out of edge shapes.

For more info, check the manual: http://www.box2d.org/manual.html#\_Toc258082970 (scroll down to 4.5).

# Answer
> 2 votes
Your problem lies in the following words

> on top of a floor composed of a series of square tiles

Essentially your box keeps getting caught on the edges of your floor. There is a great article on iforce2d.net about this, you can find it HERE. Some solutions to the problem:

* Use ghost vertices
* Replace your tiles with a single edge
* Replace a section of tiles with a single polygon
* Use a vertex clipping algorithm to remove duplicated vertices and collinear vertices (lying on the same plane/line)

# Answer
> -1 votes
Does this answer help? I've had the same issue with a pinball game and this worked for me.

---
Tags: c++, box2d
---


title: OpenGL - white edges on cubes

text:
# Question
Title: OpenGL - white edges on cubes
In a minecraft-like game I'm making, I get white edges on my cubes:

It is much more noticeable in darker textures. The textures are being setup like this: `glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);` `glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);`

Any help?

# Answer
> 19 votes
There are two possible causes for this type of problem, depending on exactly which problem it is. I'll list both:

### 1. You are seeing other colors from your texture along the edges of the tiles.

This looks to me like the problem in this case, because all of the edge pixels are one of three colors which are plausibly in your texture: white, black, and brown.

If you are using multiple tile images right next to each other in a single texture (a texture atlas), as I assume you are doing, this is inevitable. It occurs because the GPU does not perfectly match up interpolation along the edge of a triangle with interpolation along the texture, and you get little bits of the adjacent texture.

There are a number of things you can do.

* Use an *array texture* instead of a texture atlas. An array texture is made up of “layers” that are (in this case) 2D images of the same size, and you specify a third coordinate to select one; it is intended exactly as a replacement for texture atlases without the filtering problem.

Caveat: if you want to use many tiles, you may find that your GPU may not support large enough array textures to use them without any atlasing at all.
* Generate a 1-pixel border in each of your texture tiles, which replicates the color of the adjacent regular pixel. (This is essentially reimplementing GL's `CLAMP[_TO_EDGE]`, but in a way which is aware of texture atlases — your use thereof has no effect because most of your tile edges are not at the edge of the texture.) This is the solution I use in my own entry in the genre, All is Cubes (combined with array texturing for maximum capacity).

Caveat: Mipmapping, if you use it, effectively blurs the texture, so texels even further outside of the tile than 1 pixel will be sampled and you will see artifacts. This effect can be reduced by using even larger borders, at the cost of more texture memory, or you can manually generate and upload mipmaps that don't cross tile boundaries.
* Very slightly inset your texture coordinates, so that they do not go all the way to the edge of the texture tile. Doing this too much will lead to a noticeable thinness of the edges of the texture compared to pixels in the middle. It also does not help with mipmapping.
* Use a single texture per tile type. This imposes texture-switching costs.

### 2. You are seeing through gaps between tiles.

I don't think this is the problem in this case, since there is no green ground seen through the gaps, but I'm including it for completeness.

This can occur when you are not providing *exactly* the same coordinates for the vertices of the meeting edges of adjacent tiles, which usually arises due to floating-point error. For example, if you have tiles of size 0.6 and compute the right edge of the tile at `x=100` with `(100*0.6) + 0.6`, and the left edge of the tile at `x=101` with `(100*0.6)`, you will not get the exact same answer, and the difference can be visible as little specks of gaps.

The solution is to ensure that your arithmetic is consistent; some ways to do this are:

* Make sure you are not (even indirectly) computing `index*size + size`, but only `(index+1)*size`.
* Make sure that your arithmetic is exact; the easiest way to do this is to make your tile size exactly 1.0, which will result in exact integer arithmetic even if you do your calculations with 32-bit floats (up to 16 million blocks from the origin, anyway). Any power of 2 (1, 2, 4, 8, … or 0.5, 0.25, 0.125, …) will also be exact in this way.
* Use actual integers for vertex coordinate calculations; this gets you even more range.

---
Tags: opengl, rendering, lwjgl
---


title: Isometric smooth fog

text:
# Question
Title: Isometric smooth fog
I'm working on a simple 2d game with direct3d 9. It's a isometric game with diamond tiles and a staggered map. This is what I have:

As you see I have some kind of fog which is acomplished by having a fog matrix which is true (clear terrain) or false (obscure terran). But the result is very chunky. The fog moves as the player moves by tiles but not by pixels. Basically I check for every tile if there is fog, if so I just change the color of that tile:

```
D3DCOLOR tile_color = 0xffffffff;
if(scene->fog[i+mapx][j+mapy] == FOG_NONE) { tile_color = 0x666666FF; }
g_pSprite->Draw(texTilesNew,&rect,NULL, &D3DXVECTOR3(pantx,panty,0.0f), tile_color);

```

Where parameter tile\_color is:

> A Color structure. The color and alpha channels are modulated by this value. The Transparent value maintains the original source color and alpha data.

I also would like the fog to be smoother, for that I followed this "tutorial" but I haven't managed to work it it out becuase I think the tutorial implements a diferent kind of fog than I am.

http://www.appsizematters.com/2010/07/how-to-implement-a-fog-of-war-part-2-smooth/

# Answer
> 3 votes
All right, the question has become much more sophisticated, so I'll upgrade my comment to an answer.

There are lots of ways to do what you want to do. The more precise you want your lighting calculations, the more complex the program will be, so I'd advice you focus on keeping it simple, and dedicate more of your time to making the game *fun* instead of getting stuck with technical details.

But anyways, here are some methods I can think of to accomplish what you want:

1. Do the lighting as a post processing effect! You won't believe how common these simple approaches are used in AAA games. Add a black sprite spanning the entire game area, with a transparent hole in the middle. PNG and DXT support 8-bit alphas, so you can make it as smooth as you want. The main disadvantage is that the shape of the shadow is mostly static. You can do some interesting tricks by messing with the perspective matrix, but is hardly optimal.
2. If you can calculate the lighting separately for each tile, multiply the sprite color by the level of shadow at each tile, or overlay a black tile with the alpha value set to the level of shadow for each tile. The main disadvantage is that if the tiles are too large, or if the shadow range is too small, you will easily notice the variation between tiles. This is by the way, what they did in many Ultima games.
3. Instead of calculating lighting for each tile, calculate it for the borders, and let the graphics engine interpolate the lighting across each tile. To do this, set the color for each vertex of your sprite mesh, and set `SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD)`. The main problem with this solution arises with very bright lights with very short propagations. You may notice some artefacts near the center.
4. A much more complex solution would be to calculate lighting per pixel. To do this, you can set the position of your player as constants to your pixel shader, where you perform the lighting calculation. This will be precise to the pixel level, but requires you to change your graphics pipeline to the programmable one (in case you're using the fixed pipeline). This is relatively complex. The main problem with this solution (and all the other ones above) is that they don't concern sub-tile shadows. In which case...
5. You can also implement the lighting manually. This is really complex and not for the faint of heart, but also very fun. There are tons of approaches to do this, so you can start asking Prof. Google something along the lines of "2d dynamic lighting".

Good luck with your game.

# Answer
> 2 votes
Here is a simple proposal: you could try modulate the fog intensity for each cell. Here is an example of applying a simple convolution filter:

```
float fog = 0.0;
for (int dj = -3; dj <= 3; dj++)
for (int di = -3; di <= 3; di++)
    if (scene->fog[i+di+mapx][j+dj+mapy] == FOG_NONE)
        fog += 0.0903142 / (0.5 + di * di + dj * dj);
if (fog > 0.0)
    tile_color = (int)(0xff - 0x99 * fog) * 0x01010100 + 0x000000FF;

```

# Answer
> 1 votes
Instead of storing booleans in your fog matrix, you could store floating-point values. This would represent the amount of fog on each tile, between 0 and 1. Then simply blend your color depending on the tile's amount of fog:

```
float fog_amount = scene->fog[i+mapx][j+mapy];
tile_color = tile_color * (1.0f - fog_amount) + 0x666666FF * fog_amount;

```

There are probably several ways to generate this fog matrix, but one way I can think of is:

* Create your matrix as you do now (with true = no fog = 0.0, and false = full fog = 1.0),
* And apply a bit of gaussian blur on it.

**EDIT**

I'm not sure that will be necessary (this is simply an artistic choice) but if you want the fog amount to change directly with the player's moves, you'll have to generate this fog matrix using directly distances from the player. E.g. if you want a simple fog circle, that's what you could do for one tile at (i,j) in your fog matrix:

```
float distance_to_player = distance(tile_pos[i][j], player_pos);
fog[i][j] = (distance_to_player - FOG_START) / (FOG_END - FOG_START);

```

**EDIT 2**

That's if you want to keep a "tiled" fog. Overlaying a translucent image as suggested by Panda Pajama in his comments might be a *much simpler* solution, but it will give you a different result. Once again, this is an artistic choice you have to make.

---
Tags: 2d, directx, isometric, directx9
---


title: Can CCAnimations be paused?

text:
# Question
Title: Can CCAnimations be paused?
I am new to cocos2d. I am using CCAnimation. It's working fine, except I want to pause the animation occasionally. How do I do this?

Here's what I'm doing so far:

```
[mySprite runAction:[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:walkAnim]]];

```

# Answer
You can pause all the actions for a node, but not individually.

Basically you can do something like this

```
[[CCActionManager sharedManager] pauseTarget:node];

[[CCActionManager sharedManager] resumeTarget:node];

```
> 1 votes

# Answer
There's no pause per se. You can use stopAction or stopActionByTag to stop it and run it again when you want to resume.

Check the API here for these methods.
> 0 votes

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


# Question
Title: Get collision details from Rectangle.Intersects()
I have a Breakout game in which, at some point, I detect the collision between the ball and the paddle with something like this:

```
// Ball class
rectangle.Intersects(paddle.Rectangle);

```

Is there any way I can get the exact coordinates of the collision, or any details about it, with the current `XNA API`?

I thought of doing some basic calculations, such as comparing the exact coordinates of each object on the moment of the collision. It would look something like this:

```
// Ball class
if((rectangle.X - paddle.Rectangle.X) < (paddle.Rectangle.Width / 2))
    // Collision happened on the left side
else
    // Collision happened on the right side

```

But I'm not sure this is the correct way to do it.

Do you guys have any tips on maybe an engine I might have to use to achieve that? Or even good coding practices using this method?

# Answer
XNA's rectangles are pretty limited. The `Rectangle.Intersects()` method only returns a boolean result, so you'll need to do more tests yourself if you want details. You can, however, use the `Rectangle.Intersect(Rectangle, Rectangle)` method to get the rectangle where the two overlap. That will give you some information on depth and location, at least.
> 7 votes

# Answer
**Update:** If you're using MonoGame, then as of 3.0 beta, `Rectangle Rectangle.Intersect(rectangle, rectangle)` doesn't exist. You can use the below code from the XNA Platformer kit instead.

---

You can download the XNA Platformer Starter Kit (ported to Windows 7). It ships with a helper extension method that returns a rectangle describing the intersection of two rectangles:

```
static class RectangleExtensions
    {
        /// <summary>
        /// Calculates the signed depth of intersection between two rectangles.
        /// </summary>
        /// <returns>
        /// The amount of overlap between two intersecting rectangles. These
        /// depth values can be negative depending on which wides the rectangles
        /// intersect. This allows callers to determine the correct direction
        /// to push objects in order to resolve collisions.
        /// If the rectangles are not intersecting, Vector2.Zero is returned.
        /// </returns>
        public static Vector2 GetIntersectionDepth(this Rectangle rectA, Rectangle rectB)
        {
            // Calculate half sizes.
            float halfWidthA = rectA.Width / 2.0f;
            float halfHeightA = rectA.Height / 2.0f;
            float halfWidthB = rectB.Width / 2.0f;
            float halfHeightB = rectB.Height / 2.0f;

            // Calculate centers.
            Vector2 centerA = new Vector2(rectA.Left + halfWidthA, rectA.Top + halfHeightA);
            Vector2 centerB = new Vector2(rectB.Left + halfWidthB, rectB.Top + halfHeightB);

            // Calculate current and minimum-non-intersecting distances between centers.
            float distanceX = centerA.X - centerB.X;
            float distanceY = centerA.Y - centerB.Y;
            float minDistanceX = halfWidthA + halfWidthB;
            float minDistanceY = halfHeightA + halfHeightB;

            // If we are not intersecting at all, return (0, 0).
            if (Math.Abs(distanceX) >= minDistanceX || Math.Abs(distanceY) >= minDistanceY)
                return Vector2.Zero;

            // Calculate and return intersection depths.
            float depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
            float depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
            return new Vector2(depthX, depthY);
        }

        /// <summary>
        /// Gets the position of the center of the bottom edge of the rectangle.
        /// </summary>
        public static Vector2 GetBottomCenter(this Rectangle rect)
        {
            return new Vector2(rect.X + rect.Width / 2.0f, rect.Bottom);
        }
}

```
> 4 votes

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


# Question
Title: Relative positions of player and enemy are different In XNA 3D game
I am having a problem in my 3D jet fighter game using XNA. I have a player jet and a few enemy drones built from a separate class. The problem is that when I set player position and a drone's position to a height of 10f in y-direction, they aren't at the same height, but if I move a drone's position up 500f in the y-direction, then it is pretty close to the player. Relatively they are supposedly at the same height but with different position values. Can anyone help, please?

Here is the code of Enemy Class:

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace _3D_Game_Project
{
class Enemy
{
    SpriteFont Font;
    Model Drone;
    bool CanMoveForward;
    bool FlyRightNow;
    bool FlyLeftNow;
    bool TurnAroundNow;
    bool BusyInOperation;
    public bool CanCheckForCollision;
    public Matrix DroneFanRot = Matrix.Identity;
    public Matrix EnemyWorld = Matrix.Identity;
    public Vector3 Position;
    public Quaternion Rotation = Quaternion.Identity;
    public BoundingSphere DroneBounds;
    public BoundingBox LimitBox;
    public BoundingBox[] BuildingBoxes;
    public void Initialize(ContentManager Content, BoundingBox Limit, BoundingBox[] BuildingBox, Vector3 Pos)
    {
        LimitBox = Limit;
        CanCheckForCollision = true;
        BuildingBoxes = new BoundingBox[BuildingBox.Length];
        Font = Content.Load<SpriteFont>("Calibri");
        Drone = Content.Load<Model>("Drone");
        Position = Pos;
        FlyLeftNow = false;
        FlyRightNow = false;
        TurnAroundNow = false;
        BusyInOperation = false;
        CanMoveForward = true;
        //new Vector3(Position.X / 500, Position.Y / 500, Position.Z / 500)
        DroneBounds = new BoundingSphere(Position, 0.04f);
        EnemyWorld = Matrix.CreateFromQuaternion(Rotation) * Matrix.CreateTranslation(Position);
    }

    float RotatedAround = 0;
    public void TurnAround()
    {
        if (RotatedAround >= 180)
        {
            BusyInOperation = false;
            TurnAroundNow = false;
            RotatedAround = 0;
            CanMoveForward = true;
        }
        else
        {
            Rotation *= Quaternion.CreateFromYawPitchRoll(MathHelper.Pi / 60, 0, 0);
            RotatedAround += MathHelper.Pi / 60;
        }
    }

    float RotatedRight = 0;
    public void FlyRight()
    {
        if (RotatedRight >= 90)
        {
            BusyInOperation = false;
            RotatedRight = 0;
            FlyRightNow = false;
            CanMoveForward = true;
        }
        else
        {
            Rotation *= Quaternion.CreateFromYawPitchRoll(MathHelper.PiOver2/60, 0, 0);
            RotatedRight += MathHelper.PiOver2 / 60;
        }
    }
    float RotatedLeft = 0;
    public void FlyLeft()
    {
        if (RotatedLeft >= 90)
        {
            BusyInOperation = false;
            RotatedLeft = 0;
            FlyLeftNow = false;
            CanMoveForward = true;
        }
        else
        {
            Rotation *= Quaternion.CreateFromYawPitchRoll(-MathHelper.PiOver2/60, 0, 0);
            RotatedLeft += (MathHelper.PiOver2 / 60);
        }
    }
    Random Turn = new Random();
    public void SignalOperation(bool TurnDrone)
    {
        if (TurnDrone)
        {
            if (CanCheckForCollision == true)
            {
                if (BusyInOperation == false)
                {
                    BusyInOperation = true;
                    CanCheckForCollision = false;
                    if (Turn.Next(1, 150) < 50)
                    {
                        FlyLeftNow = true;
                    }
                    else if (Turn.Next(1, 150) > 50 || Turn.Next(1, 150) < 100)
                    {
                        FlyRightNow = true;
                    }
                    else if (Turn.Next(1, 150) > 100)
                    {
                        TurnAroundNow = true;
                    }
                }
            }
        }
    }
    float DelayCollision = 3;
    public void Update(Vector3 PositionOfPlayer, Quaternion RotationOfPlayer, GameTime gameTime, List<Enemy> Drones)
    {
        if (CanMoveForward)
        {
            MoveForward(ref Position, Rotation, 1.5f);
            DelayCollision -= (float)gameTime.ElapsedGameTime.TotalSeconds;
            if (DelayCollision <= 0)
            {
                CanCheckForCollision = true;
                DelayCollision = 3;
            }

        }
        if (FlyLeftNow)
        {
            CanMoveForward = false;
            FlyLeft();
        }
        else if (FlyRightNow)
        {
            CanMoveForward = false;
            FlyRight();
        }
        else if (TurnAroundNow)
        {
            CanMoveForward = false;
            TurnAround();
        }
        EnemyWorld = Matrix.CreateFromQuaternion(Rotation) * Matrix.CreateTranslation(Position);
        DroneFanRot *= Matrix.CreateRotationZ(MathHelper.PiOver4);

        DroneBounds = new BoundingSphere(Position, 0.04f);
    }

    private void MoveForward(ref Vector3 position, Quaternion rotationQuat, float speed)
    {
        Vector3 addVector = Vector3.Transform(new Vector3(0, 0, -3), rotationQuat);
        position += addVector * speed;
    }
    public void Draw(SpriteBatch spriteBatch, Matrix ViewMatrix, Matrix ProjectionMatrix)
    {
        Matrix[] EnemyTransforms = new Matrix[Drone.Bones.Count];
        Drone.CopyAbsoluteBoneTransformsTo(EnemyTransforms);
        foreach (ModelMesh Meshes in Drone.Meshes)
        {
            if (Meshes == Drone.Meshes["Propeller"])
            {
                foreach (BasicEffect effect in Meshes.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.Projection = ProjectionMatrix;
                    effect.View = ViewMatrix;
                    effect.World = EnemyTransforms[Meshes.ParentBone.Index] * EnemyWorld * Matrix.CreateScale(0.005f, 0.005f, 0.005f) * DroneFanRot;
                }
            }
            else
            {
                foreach (BasicEffect effect in Meshes.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.Projection = ProjectionMatrix;
                    effect.View = ViewMatrix;
                    effect.World = EnemyTransforms[Meshes.ParentBone.Index] * EnemyWorld * Matrix.CreateScale(0.005f, 0.005f, 0.005f);
                }
            }

            Meshes.Draw();
        }
    }
}

```

}

# Answer
> 0 votes
I finally figured out the answer to my question. It had something to do with the order of multiplication of matrices in the Draw Method.

---
Tags: xna-4.0
---


# Question
Title: Does the license of games made with Game Maker need to include the Game Maker part?
In the default license generated by Game Maker for your games, some of YoYo Games stuff is mentioned. Are those necessary to be shipped with an application made with GM? Is it legally ok if I remove those and create my own license agreement, not mentioning Game Maker or YoYo Games in it?

# Answer
*tl;dr*. Yes. That said:

*This is not legal advice.* You should seek clarification from a lawyer or from a representative of YoYo Games.

The Game Maker EULA, which you have presumably agreed to if you're using their software (unless you're using an older version to which this particular EULA does not apply, in which case you'll need to refer to it) indicates:

> The Applications and all materials accompanying the Stand-alone Applications shall include a notice and End User Licence Terms:
>
> (i) identifying the rights of YoYo Games and that they include, are based on and made using the Software;
>
> (ii) that such end user will have no right to modify, adapt, decompile or reverse engineer the Stand-alone Applications or make any use of the Software contained therein nor to permit anyone else to do so;
>
> (iii) that such end user must not remove, disable, modify, add to or tamper with any program code or data, copyright, trademark or other proprietary notices and legends contained within the object (compiled) code of the Software;

Both "Applications" and "Stand-Alone Applications" in this context are in reference to *your* games that have been produced using GameMaker. YoYo Games has provided a sample EULA, which I'm presuming is the "sample license" you're referring to, here.

What clause (i) above means is that you cannot remove references to YoYo Games or the fact that your game was created using their software. Specifically your end-user license agreement must call out all the rights that YoYo Games asserts in their EULA. You can see in the sample agreement that they do so by (among other things):

* stating the game was created using software written by YoYo Games
* asserting that the game itself is not their creation, only the software used to make it
* disclaiming liability for any damage or problems
* asserting their copyright over the aspects of the game that come directly from Game Maker

You are *not* required to use, word-for-word, the sample EULA. However, unless you consult a lawyer regarding modifications to the language or to the terms of the sample agreement, you could very easily violate the Game Maker EULA you agreed to, potentially opening yourself up to legal action.

Therefore I would recommend that you **do not try to change the license unless you do so with the blessing of your lawyer**.
> 4 votes

---
Tags: game-maker
---


# Question
Title: FBO rendering different result between Galaxy S2 and S3
I'm working on a pong game and have recently set up FBO rendering so that I can apply some post-processing shaders. This proceeds as so:

* Bind texture A to framebuffer
* Draw balls
* Bind texture B to framebuffer
* Draw texture A using fade shader on fullscreen quad
* Bind screen to framebuffer
* Draw texture B using normal textured quad shader

Neither texture A or B are cleared at any point, this way the balls leave trails on screen, see below for the fade shader.

**Fade Shader**

```
private final String fragmentShaderCode =
        "precision highp float;" +
        "uniform sampler2D u_Texture;" +
        "varying vec2 v_TexCoordinate;" +
        "vec4 color;" +
        "void main(void)" +
        "{" +
        "   color = texture2D(u_Texture, v_TexCoordinate);" +
        "   color.a *= 0.8;" +
        "   gl_FragColor = color;" +
        "}";

```

This works fine with the Samsung Galaxy S3/ Note2, but cause a strange effect doesnt work on Galaxy S2 or Note1. See pictures:

**Galaxy S3/Note2**

**Galaxy S2/Note**

Can anyone explain the difference?

**edit**

Folowing VinceFR's comment, we've tried adding the following. When the renderbuffers are initialised they are briefly bound to the framebuffer and set the background to a uniform buffer with:

```
    GLES20.glClearColor(backgroundColor[0],backgroundColor[1],backgroundColor[2],backgroundColor[3]);
    GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);

```

The result is unchanged on the S3, on the S2 it has improved a certain amount, but problems still exist:

note the 20 in the bottom right corner is supposed to be there.

# Answer
Try to draw a black background explicitly. I had a similar visual effect when I was drawing on a surface with no background.
> 1 votes

---
Tags: android, textures, opengl-es2
---


title: Queries regarding Geometry Shaders

text:
# Question
Title: Queries regarding Geometry Shaders
I am dealing with geometry shaders using GL\_ARB\_geometry\_shader4 extension.

My code goes like :

```
GLfloat vertices[] =
    {
        0.5,0.25,1.0,
        0.5,0.75,1.0,
        -0.5,0.75,1.0,
        -0.5,0.25,1.0,
        0.6,0.35,1.0,
        0.6,0.85,1.0,
        -0.6,0.85,1.0,
        -0.6,0.35,1.0
    };

glProgramParameteriEXT(psId, GL_GEOMETRY_INPUT_TYPE_EXT, GL_TRIANGLES);

glProgramParameteriEXT(psId, GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_TRIANGLE_STRIP);

glLinkProgram(psId);

glBindAttribLocation(psId,0,"Position");

glEnableVertexAttribArray (0);

glVertexAttribPointer(0, 3, GL_FLOAT, 0, 0, vertices);

glDrawArrays(GL_TRIANGLE_STRIP,0,4);

```

My vertex shader is :

```
#version 150

in vec3 Position;

void main()
{
    gl_Position = vec4(Position,1.0);

}

```

Geometry shader is :

```
#version 150
#extension GL_EXT_geometry_shader4 : enable

in vec4 pos[3];

void main()
{
   int i;
   vec4 vertex;

    gl_Position = pos[0];
    EmitVertex();

    gl_Position = pos[1];
    EmitVertex();

    gl_Position = pos[2];
    EmitVertex();

    gl_Position = pos[0] + vec4(0.3,0.0,0.0,0.0);
    EmitVertex();

    EndPrimitive();
}

```

Nothing is rendered with this code. What exactly should be the mode in glDrawArrays() ? How does the GL\_GEOMETRY\_OUTPUT\_TYPE\_EXT parameter will affect glDrawArrays() ?

What I expect is 3 vertices will be passed on to Geometry Shader and using those we construct a primitive of size 4 (assuming GL\_TRIANGLE\_STRIP requires 4 vertices). Can somebody please throw some light on this ?

# Answer
Your `vec4 pos[3]` variable in your geometry shader doesn't appear to be getting set, unless you didn't post the code for that. If it's being initialized to zero and never set, that could be why nothing shows up. If you want the geometry shader to get the positions output from the vertex shader, you need to use the built-in variable `gl_PositionIn[]` for that.

The input to `glDrawArrays` and similar must match the *input* primitive type of the geometry shader. Since you've written a geometry shader that works on triangles, you can use a triangle list, strip or fan in `glDrawArrays`. Each triangle generated by the draw call is sent to the geometry shader and processed separately, after being vertex-shaded.

So the way you have it now, you're drawing a triangle strip of 4 vertices, which creates 2 triangles; each of these is then passed to the geometry shader, which turns it into a strip of 2 triangles. So you end up with 4 triangles drawn altogether.
> 1 votes

---
Tags: opengl, glsl, geometry-shader
---


# Question
Title: Gamma-Correct rendering without floating-point rendertargets
When using a gamma-correct pipeline, you have to work with floating-point rendertargets. Otherwise, you will get severe banding due to the insufficient precision of the usual 8-bit-per-channel integer rendertargets.

Is there any way around this? Any good way to implement gamma-correct rendering without using floating-point rendertargets?

This is on desktop PCs using Windows and DirectX.

# Answer
You can keep your buffers in sRGB and convert from gamma to linear in the shader when reading a texture, and back to gamma on output. Newer GPUs even have hardware support for doing these conversions automatically. In Direct3D 10/11 you can activate this by setting up your textures and render targets with sRGB formats. It also works with blending (blending will be done in linear space).

Older (Direct3D 9) GPUs may also support gamma conversions on read and write, but still do blending in linear space, which limits the usefulness of this approach, since e.g. additive blending for accumulating light will not be correct.

Beyond that, if 8-bit sRGB isn't enough precision for you (e.g. you're doing math that introduces banding even in 8-bit sRGB, or you want to do HDR) then floating-point render targets are probably the best way.

Some GPUs/platforms support integer render targets with more than 8 bits per channel. For example, there is an R10G10B10A2 format seen sometimes. However, 10 bits still probably aren't enough to avoid the banding. This article calculates that the a minimum linear-space precision of 12 bits is needed to match 8 bits of sRGB. Some GPUs even have a 16-bit integer render target format, but I don't think this is widely supported, and I'm not sure if you can do blending, bilinear filtering, etc. with these render targets.

It's also possible to use 8-bit framebuffers with the alpha channel used to improve precision, as in LogLUV or RGBM. But again, blending does not work with such encodings. Alpha compositing may work acceptably, but additive blending does not, so accumulating lights in such formats is challenging. You have to avoid using hardware blending and write shaders that decode, update, and re-encode the format.
> 6 votes

---
Tags: lighting, pipeline
---


title: Advantages of Steam Greenlight

text:
# Question
Title: Advantages of Steam Greenlight
Let's assume that I can pick a fairly decent game, build it, and finish it with sufficient chrome plating; let's also assume that I can market it myself to some extent, through my own website.

What exactly are the advantages of going through Steam Greenlight? Assuming I can actually get through the process and reach sufficient critical mass to be "Greenlight." Do you know what usually becomes of finished, polished, chrome-plated games that get "greenlit?" Statistically, does greenlighting correlate with commercial success or higher sales?

By the way, I'm assuming my marketing sucks, and that Steam, in general, gets *some* eyeballs and sales for you.

# Answer
> 8 votes
One advantage, even if you don't get your game Greenlit, is exposure. Greenlight actually drives traffic to your website, since the large volume of Steam users do stumble across your Greenlight page and may visit your website from there.

So even if you aren't Greenlit, it's still a useful marketing tool to drive traffic to your website and gain exposure.

Source: I have a game on Steam Greenlight

# Answer
> 6 votes
Your question could be renamed to "Will having millions of people seeing my game improve my sales?"

**People will only buy your game if they know of it.** When your game is greenlit, it will be published and more importantly "announced" on Steam. Which means most people who use Steam (50 million according to Wikipedia) will get notified that your game is available.

That's a insane amount of people and will result in a lot sales, probably enough to form a critical mass (that's it, that enough people talk about your game that your game will make constantly sales without being announced on other platforms).

Note however, that you already need publicity to get the game greenlit at all. That's not easy at all. Greenlight is not made to live solely on it's own but rather that you have to bring the people to vote for your game, it's not possible to reach the greenlight amount of votes without having a big community already.

On the other side, being on Greenlight is already a form of publicity, which will bring more people to your game than most other platforms will.

# Answer
> 4 votes
Since you're already assuming you have a good game, and it's popular enough to make it through the Greenlight process, you don't have much to worry about. Once you have enough critical mass to get Greenlight, people will have voted to get your game there, it's highly likely that at least some portion of them will also buy the game once it's on Steam. Additionally, once it's available on Steam, you have a much larger market that will now see and have the ability to easily purchase your game.

So, yes, you can expect more marketing and thus sales. If you have Steam selling your game, you'll have more sales and marketing. Certainly a lot more than if you never had your game on Steam. I can't imagine a situation where you'd have fewer people knowing about your game or fewer sales as a result of getting Greenlight. You can find some statistics for Greenlight games here. And an article here.

Steam is typically very tight with marketing numbers. Even within the Greenlight program you don't have exact numbers for how many people need to vote in order to make your game Greenlight. It's highly unlikely you'll be able to find statistics that show before/after for Greenlight games. Steam doesn't like people sharing their revenue information about games sold on Steam either, so it's even more unlikely. There are some hints here and there. All in all, things point to the obvious, getting your game on Steam is better than not being on Steam.

**With the assumptions you make, you are nearly guaranteed some form of success.**

---
Tags: marketing, steam
---


title: DirectX Unproject troubles

text:
# Question
Title: DirectX Unproject troubles
I have an orthographic projection and I try to unproject a point from screen space.

Following are the view and projection matrices:

```
var w2 = ScreenWidthInPixels/2;
var h2 = ScreenHeightInPixels/2;

view  = Matrix.LookAtLH(new Vector3(0, 0, -1), new Vector3(0, 0, 0),
                        Vector3.UnitY);
proj  = Matrix.OrthoOffCenterLH(-w2, w2, -h2, h2, 0.1f, 10f);

```

Here is how I unproject a Point `p`, the point is given in screen pixels:

```
var m = Vector3.Unproject(p, 0, 0, ScreenWidthInPixels, ScreenHeightInPixels,
                  0.1f, 10f, // znear and zfar
                  view *proj);

```

My code doesn't work, the matrix `m` contains only `Nan`. When I try to invert `view * proj` I get back a Matrix with only zeros.

So I suspect my problem has something to do with the orthographic projection matrix.

Here are my questions:

* Could the problem be caused by an underflow due to the large values in the OrthoOffCenterLH projection?
* What parameters do I have to pass for `x,y,width,height` in `Unproject(...)`?
* What significance has the `minZ` and `maxZ` parameter in `Unproject(...)`?
* Does it matter what I pass for `p.Z` in `Unproject(...)`?

# Answer
> 3 votes
> Could the problem be caused by an underflow due to the large values in the OrthoOffCenterLH projection?

Don't know exactly what you mean. But no, this seems to neither be an issue with precision or overflow/underflow.

> What parameters do I have to pass for x,y,width,height in Unproject(...)?

Straight from the documentation
(x,y) is the location of the viewport, (0,0) should be fine. (width,height) is exactly what you pass in, the width and height of the viewport.

> What significance has the minZ and maxZ parameter in Unproject(...)?

These are simply your near and far clipping planes. Read up on projections here. The article is geared towards OpenGL, but is actually quite agnostic and mostly math. Basically they have to match what you pass in for your OrthoOffCenterLH() call.

> Does it matter what I pass for p.Z in Unproject(...)?

Yes it does. Z needs to be the *depth value*. Think about it this way, you have a point p that you multiplied by your model and view matrices. To project, you multiply p by the projection matrix.

But this conversion doesn't lop off the original Z value and just give you 2D x and y, it also gives you a depth value that gets written to the depth buffer. Without this depth value, how do you think you can unproject a 2D point back into 3D?

You will either need to read the depth buffer at the x,y coordinate you wish to unproject or compute this depth value your self.

---
Tags: 3d, directx, directx11, sharpdx
---


# Question
Title: Interpolating between two networked states?
I have many entities on the client side that are simulated (their velocities are added to their positions on a per frame basis) and I let them dead reckon themselves. They send updates about where they were last seen and their velocity changes. This works great and other players see this work find. However, after a while these players begin to desync after some time. This is because of latency.

I'd like to know how I can interpolate between states so they appear to be in the correct position. I know where the player was LAST seen and their current velocity but interpolating to the last seen state causes the player to actually move -backwards-. I could not use velocity at all for other clients and simply 'lerp' them towards the appropriate direction but I feel this would cause jaggy movement. What are the alternatives?

# Answer
For this reason, you'll find simulations are often run 1 or more frames *ahead* of what is in fact being rendered at given point in time on a give client. So in other words, what you render might in fact be the second last frame, not the last frame.

Search this article for all instances of the word "ahead" and I think you will start to get the picture better than I may have explained it above.
> 9 votes

# Answer
When you say:

> these players begin to desync after some time

it makes me think that your issue may have more to do with your clocks getting out of step than with any latency issues. If it's latency, it should be just as bad at the start than 10 minutes in. If one game clock is running slightly faster than the other, there will be some weird jitter artifacts that will get worse and worse over time. A client could be simulating in the future, when the present packets arrive from the server, it'll pull the client back, causing entities to jump around. Run some more tests to find out.

If out of sync game clocks are indeed an issue, you'll need to look very carefully at your update loop and make sure that every update is based on the amount of game-time passed (either fixed or variable), and that the game-time is advanced using something like the wall-clock (not render time or other variables). Gaffer has some good articles on this, and there's a decent question on here talking about fixed vs variable timesteps. Hope this helps.
> 2 votes

---
Tags: c#, movement, interpolation
---


title: Complexity of defense AI

text:
# Question
Title: Complexity of defense AI
I have a non-released game, and currently it's only possible to play with another human being. As the game rules are made up by me, I think it would be great if new players could learn basic game play by playing against an AI opponent. I mean it's not like Tennis, where the majority knows at least the fundamental rules.

On the other hand, I'm a bit concerned that this AI implementation can be quite complex. I hope you can help me with an complexity estimation. I've tried to summarize the gameplay below. Is this defense AI very hard to do?

**Basic Defense Game Play**

Player *Defender* can move within his land, i.e. inside a random, non-convex, polygon. This land will also contain obstacles modeled as polygons, that *Defender* has to move around. Player *Attacker* has also a land, modeled as another such polygon.

Assume that *Defender* shall defend against *Attacker*. *Attacker* will then throw a thingy towards *Defender*'s land. To be rewarded, *Attacker* wants to hit *Defender*'s land, and *Defender* will want to strike away the thingy from his land before it stops to prevent *Attacker* from scoring.

To feint *Defender*, *Attacker* might run around within his land before the throw, and based on these attacker movements *Defender* shall then continuously move to the best defense position within his land.

# Answer
That sounds pretty complex to me :/

As an alternative, perhaps you can make a scripted tutorial that the user can step through. If all the events are pre-determined you won't need any AI at all.

Otherwise you'll need to break down each component (as DampeS8N suggests). Identify the actions you'll need your AI to take. Finding a path, targeting a "thingy" and hitting it away are all things you'll need to do. As you delve deeper into this, you'll find a dozen more little things you'll need to detect/react to.
> 1 votes

---
Tags: ai, path-finding
---


# Question
Title: Need Guidance Making HTML5 Canvas Game Engine
So I have some free time this winter break and want to build a simple 2d HTML5 canvas game engine. Mostly a physics engine that will dictate the way objects move and interact(collisions, etc). I made a basic game here:

http://caidenhome.com/HTML%205/pong.html

and would like to make more, and thought that this would be a good reason to make a simple framework for this stuff. Here are some questions:

* Does the scripting language have to be Javascript? What about Ruby? I will probably write it with jQuery because of the selecting powers, but I'm curious either way.
* Are there any great guides you guys know of? I want a fast guide that will help me bust out this engine sometime in the next 2 weeks, hopefully sooner.
* What are some good conventions I should be aware of?
* What's the best way to get sound? At the moment I'm using something like this:

var audioElement = document.createElement('audio'); audioElement.setAttribute('src', 'paddle\_col.wav'); audioElement.load();

I'm interested in making this engine lightweight and extremely efficient, I will do whatever it takes to get great speeds and processing power. I know this question is fairly vague, but I just need a push in the right direction.

Thanks :)

# Answer
> 4 votes
*Q. Does the scripting language have to be Javascript?*

A. Yes. There are other somewhat supported scripting languages, but JavaScript is by far the easiest to get into, most widely supported, and most widely documented. In terms of JS toolkits available, jQuery is certainly an option. So is Dojo Toolkit; with its AMD design scheme, it's (arguably) the better choice if you're looking to develop long-term. It's the toolkit I decided to go to when developing my own game engine, TGE.

*Q: Are there any great guides you guys know of?*

A: Yes! The Mozilla Developer Network is a great guide on all things HTML5. It will provide you with the basic skills necessary to manipulate HTML5 DOM elements. However, game development theory is still king; you'll at least need to understand things like separating the physics and animation loops, sprite animation, scene management (yes, PONG has a scene, and there are objects in it which need management). Then there are paradigms like event-driven (vs. function-driven) programming, callbacks, the execution context stack, and so on. I'd suggest reading through The Good Parts, The Definitive Guide (if you've got time), and Patterns.

Q: What are some good conventions I should be aware of?

A: I chose the "do everything in JavaScript" path, and avoid authoring DOM elements in HTML where possible. I'm not sure if this is highly desirable, but it makes the most sense to me to keep as much in JS where possible. YMMV

Breaking down your game into Modules ("singleton"-esque interface-style, uh, interfaces like Graphics and Network and Audio) and Factories (which produce Objects like Sprites and Bullets and ParticleEmitters and PowerUps) is crucial for debugging, and important for organizing your code, especially as your project grows. A toolkit like Dojo (and to some extent, RequireJS) trumps jQuery in terms of usefulness in this regard, which is why I highly tout it.

Develop using Google Chrome, and use Chrome Developer Tools (CDT) to debug your application. Seriously. Firefox+Firebug is nice, but Chrome+CDT beats the pants off it.

Use requestAnimationFrame in your render loop.

Write your game such that it will function in all browsers which support the bare minimum elements you're planning on using. That does **not** mean supporting IE6, but it **does** mean making sure your game functions in IE9/10, Firefox, Chrome, and possibly Safari and Opera. You'll learn a lot on making your game compatible with different browsers. Don't waste your time on backward compatibility (or "progressive enhancement"), as people who are using old browser (aside from, say, your parents) won't even be looking at your game.

Trailing comma of death is your enemy.

If you're developing in Windows, Notepad++ is a great editor, and XAMPP is a great web-server stack.

If you're going to eventually write some server-side code, PHP, C#, are great options for server-side scripting languages. Other very popular languages include Ruby, but my experience is limited to the two former, so I won't comment more than that.

*Q: What's the best way to get sound?*

A: Support OGG and MP3, and you'll cover the bases you need to enable playback in the Big Three browsers. Create your audio tags once at application startup, keep the audio elements around a long time, and reuse them as often as you can, to avoid manipulating the DOM excessively.

Good luck, and happy JavaScripting!

# Answer
> 2 votes
The scripting language has to be Javascript or something which compiles into it. I recommend that you do use Javascript. There are a lot of problems with Javascript - such as its lack of a single standard way of "doing things". Defining classes, inheritance, modularity etc, all have multiple approaches which different authors do differently (or even a mixture).

However, if you don't use Javascript, you'll have to use a language which compiles into JS, and debugging becomes more difficult (because the in-browser debuggers can't see your original source code and therefore won't be source-level debuggers). It is likely to be difficult to debug any Ruby code which is compiled to Javascript.

I recommend you don't use JQuery because I don't like it, and it provides few useful features for game developers. Most games will use only a few DOM elements and they're unlikely to change much (if you mostly use a canvas).

As far as audio is concerned - I think you're best to test it on your intended target platforms and choose the approach which best works for you. Things change quickly, and when your game is ready for audio, there may be better platform support for different APIs.

# Answer
> 2 votes
I'm not attempting a complete answer, since there are already two that cover the bases rather well. I'll just add the following:

* jQuery is not a scripting language. It's a JavaScript framework/library for easing DOM manipulation and some other things, but it plays no big part when drawing things to canvas. And you want to be drawing things to canvas, maybe even with WebGL, (instead of DOM manipulation) if you want to get good performance (although CSS3D could potentially perform better than 2d canvas on some platforms). In addition, if you want to "do whatever it takes to get great speeds and processing power" you don't want to add another processing layer (jQuery) between the calls to DOM API.
* With regards to sound effects, you want to preload them and have multiple copies of each so that you can have the same sound playing multiple times at the same time (think of a machine gun that makes the shooting sound again before the previous bullet has yet finished playing).
* Game engines themselves are useless. You should be making a game. Only by actually creating a complete game you will know what is actually required from the engine. Then make another. After that you will notice which parts are reusable, which need refactoring etc. and the engine starts to take form. Afterwards, you can also show that your engine was capable of making these games, which will be a huge marketing point if you ever want anybody else using the engine.

---
Tags: 2d, html5, html-canvas, physics-engine
---


# Question
Title: Apply force to a specific point on a rigid body
In unity I have a rigid body object and would like to apply force to a specific point. For example say I had a cube, I want to hit just the top right corner so it spins as a result. One idea I had considered is spawn a small sphere and fire it at it, then destroy the sphere. But is there a way to just apply the force?

# Answer
http://docs.unity3d.com/Documentation/ScriptReference/Rigidbody.AddForceAtPosition.html

```
void ApplyForce(Rigidbody body) {
    Vector3 direction = body.transform.position - transform.position;
    body.AddForceAtPosition(direction.normalized, transform.position);
}

```
> 3 votes

---
Tags: physics, unity
---


# Question
Title: If I have a character on the screen, how do I make it look in the direction my mouse is pointing?
> **Possible Duplicate:**
> Set sprite to face direction of mouse

I'm drawing a character on the screen, and I would like it so that the character is looking where my mouse is pointing. It's a birds eye view, and the character moves as well. Also any pathfinding collision tutorials would be appreciated

# Answer
> 2 votes
Suppose you had

```
Vector2 characterPosition; //on viewport
float characterRotation; //in radians

```

Suppose you also had the current mouse position

```
MouseState mouseState = Mouse.GetState();
Vector2 mousePosition = new Vector2(mouseState.X, mouseState.Y);

```

Then you could calculate the vector that points from character to mouse position

```
Vector2 dPos = mousePosition - characterPosition;

```

You could then use `Math.Atan2` to get the angle that this vector forms with positive x axis. That would be the needed angle for the character, so you set it for your characters rotation:

```
characterRotation = (float)Math.Atan2(dPos.Y, dPos.X);

```

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


title: Ingame menu is not working correctly

text:
# Question
Title: Ingame menu is not working correctly
The ingame menu opens when the player presses Escape during the main game. If the player presses Y in the ingame menu, the game switches to the main menu. Up to here, everything works. But: On the other hand, if the player presses N in the ingame menu, the game should switch back to the main game(should resume the main game). But that doesn't work. The game just rests in the ingame menu if the player presses N. I set a breakpoint in this line of the Ingamemenu class:

```
KeyboardState kbState = Keyboard.GetState();

```

CurrentSate/currentGameState and LastState/lastGameState have the same state: IngamemenuState. But LastState/lastGameState should not have the same state than CurrentSate/currentGameState. What is wrong? Why is the ingame menu not working correctly?

```
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    IState lastState, currentState;

    public enum GameStates
    {
        IntroState = 0,
        MenuState = 1,
        MaingameState = 2,
        IngamemenuState = 3
    }

    public void ChangeGameState(GameStates newState)
    {
        lastGameState = currentGameState;
        lastState = currentState;
        switch (newState)
        {
            case GameStates.IntroState:
                currentState = new Intro(this);
                currentGameState = GameStates.IntroState;
                break;
            case GameStates.MenuState:
                currentState = new Menu(this);
                currentGameState = GameStates.MenuState;
                break;
            case GameStates.MaingameState:
                  currentState = new Maingame(this);
                  currentGameState = GameStates.MaingameState;
                break;
            case GameStates.IngamemenuState:
                currentState = new Ingamemenu(this);
                currentGameState = GameStates.IngamemenuState;
                break;
        }
        currentState.Load(Content);
    }

    public void ChangeCurrentToLastGameState()
    {
        currentGameState = lastGameState;
        currentState = lastState;
    }

    public GameStates CurrentState
    {
        get { return currentGameState; }
        set { currentGameState = value; }
    }

    public GameStates LastState
    {
        get { return lastGameState; }
        set { lastGameState = value; }
    }

    private GameStates currentGameState = GameStates.IntroState;
    private GameStates lastGameState;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {
        ChangeGameState(GameStates.IntroState);
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        currentState.Load(Content);
    }

    protected override void Update(GameTime gameTime)
    {
        currentState.Update(gameTime);
        if ((lastGameState == GameStates.MaingameState) && (currentGameState == GameStates.IngamemenuState))
        {
            lastState.Update(gameTime);
        }
        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        if ((lastGameState == GameStates.MaingameState) && (currentGameState == GameStates.IngamemenuState))
        {
          lastState.Render(spriteBatch);
        }
        currentState.Render(spriteBatch);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

public interface IState
    {
        void Load(ContentManager content);
        void Update(GameTime gametime);
        void Render(SpriteBatch batch);
    }

public class Intro : IState
{
    Texture2D Titelbildschirm;
    private Game1 game1;

    public Intro(Game1 game)
    {
        game1 = game;
    }

    public void Load(ContentManager content)
    {
       Titelbildschirm = content.Load<Texture2D>("gruft");
    }

    public void Update(GameTime gametime)
    {
        KeyboardState kbState = Keyboard.GetState();
        if (kbState.IsKeyDown(Keys.Space))
            game1.ChangeGameState(Game1.GameStates.MenuState);
    }

    public void Render(SpriteBatch batch)
    {
        batch.Draw(Titelbildschirm, new Rectangle(0, 0, 1280, 720), Color.White);
    }
}

public class Menu:IState
{
Texture2D Choosescreen;
private Game1 game1;

    public Menu(Game1 game)
    {
        game1 = game;
    }

public void Load(ContentManager content)
{
    Choosescreen = content.Load<Texture2D>("menubild");
}

public void Update(GameTime gametime)
{
    KeyboardState kbState = Keyboard.GetState();
    if (kbState.IsKeyDown(Keys.Enter))
        game1.ChangeGameState(Game1.GameStates.MaingameState);
    if (kbState.IsKeyDown(Keys.Escape))
        game1.Exit();
}

public void Render(SpriteBatch batch)
{
    batch.Draw(Choosescreen, new Rectangle(0, 0, 1280, 720), Color.White);
}
}

public class Maingame : IState
{
    Texture2D Spielbildschirm, axe;
    Vector2 position = new Vector2(100,100);

    private Game1 game1;

    public Maingame(Game1 game)
    {
        game1 = game;
    }

    public void Load(ContentManager content)
    {
        Spielbildschirm = content.Load<Texture2D>("hauszombie");
        axe = content.Load<Texture2D>("axxx");
    }

    public void Update(GameTime gametime)
    {
          KeyboardState keyboardState = Keyboard.GetState();
          float delta = (float)gametime.ElapsedGameTime.TotalSeconds;
          position.X += 5 * delta;
          position.Y += 3 * delta;

          if (keyboardState.IsKeyDown(Keys.Escape))
            game1.ChangeGameState(Game1.GameStates.IngamemenuState);
    }

    public void Render(SpriteBatch batch)
    {
        batch.Draw(Spielbildschirm, new Rectangle(0, 0, 1280, 720), Color.White);
        batch.Draw(axe, position, Color.White);
    }
}

public class Ingamemenu : IState
{
    Texture2D Quitscreen;
    private Game1 game1;

    public Ingamemenu(Game1 game)
    {
        game1 = game;
    }

    public void Load(ContentManager content)
    {
        Quitscreen = content.Load<Texture2D>("quit");
    }

    public void Update(GameTime gametime)
    {
        KeyboardState kbState = Keyboard.GetState();
        if (kbState.IsKeyDown(Keys.Y))
           game1.ChangeGameState(Game1.GameStates.MenuState);
        if (kbState.IsKeyDown(Keys.N))
          game1.ChangeCurrentToLastGameState();
    }

    public void Render(SpriteBatch batch)
    {
        batch.Draw(Quitscreen, new Rectangle(200, 200, 200, 200), Color.White);
    }
}

```

# Answer
Well, I have a guess.

You need to hit ESC faster :)

You have this code in your update:

```
if ((lastGameState == GameStates.MaingameState) &&
   (currentGameState == GameStates.IngamemenuState))
{
    lastState.Update(gameTime);
}

```

So that means when you're in `IngamemenuState` your game continues to update the last state `MaingameState`.

And in your `MaingameState` update you have this code:

```
if (keyboardState.IsKeyDown(Keys.Escape))
    game1.ChangeGameState(Game1.GameStates.IngamemenuState);

```

So unless you're super fast on hitting that ESC key, you're going to trigger this line twice (just twice because after `lastGameState` is updated again, `MaingameState` no longer gets updated):

```
game1.ChangeGameState(Game1.GameStates.IngamemenuState);

```

So, you're likely changing multiple times into `IngamemenuState`, which makes your last state and previous states both `IngamemenuState`.

Try setting a printout in your `ChangeGameState` function showing the previous and next states. I'm guessing you'll see two printouts

```
MaingameState -> IngamemenuState

```

and

```
IngamemenuState -> IngamemenuState

```

---

Try changing this:

```
 if (keyboardState.IsKeyDown(Keys.Escape))
     game1.ChangeGameState(Game1.GameStates.IngamemenuState);

```

to this:

```
 if (keyboardState.IsKeyDown(Keys.Escape) && game1.currentState != IngamemenuState)
     game1.ChangeGameState(Game1.GameStates.IngamemenuState);

```

Or something like that. Basically, you don't want to change into the menu, if you're already in the menu.

Better yet, just do the check inside your `ChangeGameState` function:

```
 if(newState == currentGameState)
     return;

```

You should also be checking all your inputs so you don't duplicate commands like this.
> 1 votes

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


# Question
Title: Are there any pitfalls with this approach to isometric map generation?
First of all, I don't have much experience on game development but I do have experience on development. I do know how to make a map, but I don't know if my solution is a normal or a hacky solution. I don't want to waste my time coding things, and realise they're utterly crap and lose my motivation.

---

Let's imagine the following map. (2D - top view - A square)

X: 0 to 500 Y: 0 to 500

My character currently stands at X:250,Y:400, somewhere near center of 100px above bottom and I can control him with my keyboard buttons. LEFT button does X--, UP button does Y-- etc.

This one is kid's play.

I'm asking this because I know there are some engines that automate this task. For example, games like Diablo 3 uses an engine. You can pretty much drag drop a rock to map, and it is automatically being placed here - making player unable to pass through/detect the collision. But what the engine exactly does in the background? Generates a map like mine, places a rock at the center, and checks it like:

```
unmovableObjects = array('50,50'); //we placed a rock at 50,50 location

if(Map.hasUnmovableObject(CurrentPlayerX, CurrentPlayerY))
{
     //unable to move
}
else
{
     //able to move
}

```

My question is: Is this how 2D/Isometric maps are being generated or there is a different and more complex logic behind them?

# Answer
One old style navi-map combines immovability/navigability with object ID - generally was a one byte bit field per map coordinate, thus a matrix (well, an array) of bytes:

```
0x00 = empty space
0x80 = wall
0xff = user character
0x01 = terrain/object 1
0x81 = impassable/immovable 1

```

etc. even more likely for character-based "graphical" maps, the actual ASCII code of the character to be displayed in each tile would be the object ID.

Nowadays, folks don't much care about how much memory these data structures use, nor how efficient the logic is, so you end up with matrices (or arrays of arrays) of objects (or structs) that have properties (fields) for every possible attribute, and methods (function pointers) for all "standard"/common actions on or by that object.
> 2 votes

---
Tags: c++, isometric
---


# Question
Title: How can I attach a model to the bone of another model?
I am trying to attach one animated model to one of the bones of another animated model in an XNA game.

I've found a few questions/forum posts/articles online which explain how to attach a weapon model to the bone of another model (which is analogous to what I'm trying to achieve), but they don't seem to work for me.

So as an example: I want to attach Model A to a specific bone in Model B.

Question 1. As I understand it, I need to calculate the transforms which are applied to the bone on Model B and apply these same transforms to every bone in Model A. Is this right?

Question 2. This is my code for calculating the Transforms on a specific bone.

```
private Matrix GetTransformPaths(ModelBone bone)
{
    Matrix result = Matrix.Identity;
    while (bone != null)
    {
        result = result * bone.Transform;
        bone = bone.Parent;
    }
    return result;
}

```

The maths of Matrices is almost entirely lost on me, but my understanding is that the above will work its way up the bone structure to the root bone and my end result will be the transform of the original bone relative to the model.

Is this right?

Question 3. Assuming that this is correct I then expect that I should either apply this to each bone in Model A, or in my Draw() method:

```
private void DrawModel(SceneModel model, GameTime gametime)
{
    foreach (var component in model.Components)
    {
        Matrix[] transforms = new Matrix[component.Model.Bones.Count];
        component.Model.CopyAbsoluteBoneTransformsTo(transforms);

        Matrix parenttransform = Matrix.Identity;
        if (!string.IsNullOrEmpty(component.ParentBone))
            parenttransform = GetTransformPaths(model.GetBone(component.ParentBone));

        component.Player.Update(gametime.ElapsedGameTime, true, Matrix.Identity);

        Matrix[] bones = component.Player.GetSkinTransforms();

        foreach (SkinnedEffect effect in mesh.Effects)
        {
            effect.SetBoneTransforms(bones);

            effect.EnableDefaultLighting();
            effect.World = transforms[mesh.ParentBone.Index]
                * Matrix.CreateRotationY(MathHelper.ToRadians(model.Angle))
                * Matrix.CreateTranslation(model.Position)
                * parenttransform;
            effect.View = getView();
            effect.Projection = getProjection();
            effect.Alpha = model.Opacity;
        }
    }
    mesh.Draw();
}

```

I feel as though I have tried every conceivable way of incorporating the parenttransform value into the draw method. The above is my most recent attempt. Is what I'm trying to do correct? And if so, is there a reason it doesn't work?

The above Draw method seems to transpose the models x/z position - but even at these wrong positions, they do not account for the animation of Model B at all.

Note: As will be evident from the code my "model" is comprised of a list of "components". It is these "components" that correspond to a single "Microsoft.Xna.Framework.Graphics.Model"

# Answer
> 1 votes
Okay this is how I got it to work. It is by no means elegant. It is based off of the SkinnedModelSample. My game has a collection of AnimatedModels - which in turn have a dictionary of other Animated Models. The string key for this dictionary is the name of the bone which it inherits it transforms from (or is "attached" to). A limitation of this is that only one model can be attached to a specific bone. (This could be easily changed, but there is no need as it meets my requirements).

```
public class AnimatedModel
{
    public Model Model { get; set; }
    public SkinningData SkinningData { get; set; }
    public AnimationPlayer Player { get; set; }
    public AnimationClip Clip { get; set; }
    public Dictionary<string, AnimatedModel> Components { get; set; }

    public AnimatedModel() : base() { }
    public AnimatedModel(Model model)
    {
        Model = model;
        Components = new Dictionary<string, AnimatedModel>();

        SkinningData = model.Tag as SkinningData;
        if (SkinningData != null)
        {
            Player = new AnimationPlayer(SkinningData);
            Clip = SkinningData.AnimationClips["ArmatureAction"];
            Player.StartClip(Clip);
        }
    }

    public void AddModel(string parentBone, Model model)
    {
        Components.Add(parentBone, new AnimatedModel(model));
    }
}

```

My Update() and Draw() methods:

```
protected override void Update(GameTime gameTime)
{
    foreach (var model in CurrentScene.GetModels().Where(x => x.IsVisible))
        UpdateModelAnimation(model.Model, gameTime, Matrix.Identity);
    base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
    graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

    GraphicsDevice.DepthStencilState = DepthStencilState.Default;
    foreach (var model in CurrentScene.GetModels().Where(x => x.IsVisible))
        DrawModel(model, model.Model);

    base.Draw(gameTime);
}

```

And Update and Draw methods for individual models:

```
private void UpdateModelAnimation(AnimatedModel model, GameTime gameTime, Matrix rootTransform)
{
    model.Player.Update(gameTime.ElapsedGameTime, true, rootTransform);
    var bones = model.Player.GetWorldTransforms();

    foreach (var item in model.Components)
    {
        ModelBone parentbone = model.Model.Bones.Where(x => x.Name == item.Key).Single();
        UpdateModelAnimation(item.Value, gameTime, bones[model.SkinningData.SkeletonHierarchy[parentbone.Index - 2]]);
    }
}

private void DrawModel(SceneModel sceneModel, AnimatedModel model)
{
    Matrix[] transforms = new Matrix[model.Model.Bones.Count];
    model.Model.CopyAbsoluteBoneTransformsTo(transforms);
    Matrix[] bones = model.Player.GetSkinTransforms();

    foreach (ModelMesh mesh in model.Model.Meshes)
    {
        foreach (SkinnedEffect effect in mesh.Effects)
        {
            effect.SetBoneTransforms(bones);

            effect.EnableDefaultLighting();
            effect.World = Matrix.CreateRotationY(MathHelper.ToRadians(sceneModel.Angle))
                * Matrix.CreateTranslation(sceneModel.Position);
            effect.View = getView();
            effect.Projection = getProjection();
            effect.Alpha = sceneModel.Opacity;
        }
        mesh.Draw();
    }
    foreach (var item in model.Components)
        DrawModel(sceneModel, item.Value);
}

```

The UpdateModelAnimations and DrawModel methods are recursive and work their way down a hierarchy of attached models. In this way it is possible to have models attached to models attached to models - indefinitely.

Of particular note is this line:

```
UpdateModelAnimation(item.Value, gameTime, bones[model.SkinningData.SkeletonHierarchy[parentbone.Index - 2]]);

```

The "parentbone.Index - 2" is used because my models (for some unresolved reason) have two additional bones which are not part of the SkinningData. So depending on how your models are created you may need to change this line.

In any case this is how I resolved the issue of attaching one animated model to the bone of another.

I haven't touched the project for a while, so I don't know if and when I'll be able to update with a more refined version of the code, but hopefully this will help others who are struggling with the same problem.

---
Tags: xna, matrix, models, transformation
---


# Question
Title: DirectX11 CreateWICTextureFromMemory Using PNG
I've currently got textures loading using CreateWICTextureFromFile however I'd like a little more control over it, and I'd like to store images in their byte form in a resource loader. Below is just two sets of test code that return two separate results and I'm looking for any insight into a possible solution.

```
ID3D11ShaderResourceView* srv;

std::basic_ifstream<unsigned char> file("image.png", std::ios::binary);

file.seekg(0,std::ios::end);
int length = file.tellg();
file.seekg(0,std::ios::beg);

unsigned char* buffer = new unsigned char[length];
file.read(&buffer[0],length);

file.close();

HRESULT hr;
hr = DirectX::CreateWICTextureFromMemory(_D3D->GetDevice(), _D3D->GetDeviceContext(), &buffer[0], sizeof(buffer), nullptr, &srv, NULL);

```

As a return for the above code I get Component not found.

```
std::ifstream file;
ID3D11ShaderResourceView* srv;

file.open("image.png", std::ios::binary);

file.seekg(0,std::ios::end);
int length = file.tellg();
file.seekg(0,std::ios::beg);

std::vector<char> buffer(length);
file.read(&buffer[0],length);

file.close();

HRESULT hr;
hr = DirectX::CreateWICTextureFromMemory(_D3D->GetDevice(), _D3D->GetDeviceContext(), (const uint8_t*)&buffer[0], sizeof(buffer), nullptr, &srv, NULL);

```

The above code returns that the image format is unknown.

I'm clearly doing something wrong here, any help is greatly appreciated. Tried finding anything even similar on stackoverflow, and google to no avail.

# Answer
Hopefully someone trying to do the same thing will find this solution.

Below is the code I used to solve this problem.

```
std::basic_ifstream<unsigned char> file("image.png", std::ios::binary);

if (file.is_open())
{
    file.seekg(0,std::ios::end);
    int length = file.tellg();
    file.seekg(0,std::ios::beg);

    unsigned char* buffer = new unsigned char[length];
    file.read(&buffer[0],length);
    file.close();

    HRESULT hr;
    hr = DirectX::CreateWICTextureFromMemory(_D3D->GetDevice(), _D3D->GetDeviceContext(), &buffer[0], (size_t)length, nullptr, &srv, NULL);
}

```

The important change being `(size_t)length` in `CreateWICTextureFromMemory`

It was indeed a stupid error.
> 1 votes

---
Tags: directx, directx11
---


title: Example of Data Oriented Design

text:
# Question
Title: Example of Data Oriented Design
I can't seem to find a nice explanation of the Data Oriented Design for a generic zombie game (it's just an example, pretty common example).

Could you make an example of the Data Oriented Design on creating a generic zombie class? Is the following good?

Zombie list class:

```
class ZombieList {
    GLuint vbo; // generic zombie vertex model
    std::vector<color>;    // object default color
    std::vector<texture>;  // objects textures
    std::vector<vector3D>; // objects positions
public:
    unsigned int create(); // return object id
    void move(unsigned int objId, vector3D offset);
    void rotate(unsigned int objId, float angle);
    void setColor(unsigned int objId, color c);
    void setPosition(unsigned int objId, color c);
    void setTexture(unsigned int, unsigned int);
    ...
    void update(Player*); // move towards player, attack if near
}

```

Example:

```
Player p;

Zombielist zl;
unsigned int first = zl.create();
zl.setPosition(first, vector3D(50, 50));
zl.setTexture(first, texture("zombie1.png"));
...

while (running) { // main loop
    ...
    zl.update(&p);
    zl.draw(); // draw every zombie
}

```

Or would creating a generic World container that contains every action from `bite(zombieId, playerId)` to `moveTo(playerId, vector)` to `createPlayer()` to `shoot(playerId, vector)` to `face(radians)/face(vector)`; and contains:

```
std::vector<zombie>
std::vector<player>
...
std::vector<mapchunk>
...
std::vector<vbobufferid> player_run_animation;
...

```

be a good example?

Whats the proper way to organize a game with DOD?

# Answer
> 11 votes
There is no such thing as a "game with DOD". Firstable, that buzz-word is a bit fuzzy, because each system is designed data-oriented. Each program works on a set of data and makes certain transformations to it. Impossible to do that without orienting the design towards the data. So it's not mutually exclusive with "normal" design, but adds constraints in memory layout and the way memory is accessed respectively.

The idea behind DOD is to pack and group data belonging to one functionality closer together in a continious memory block, in order to have less cache misses, getting rid of virtual functions and vtables, easier parallelization, no (or minimal) random memory accesses and to write code for highly optimized processors like the Cell's SPUs in the PS3 with its limited memory resources, optimizing memory access and DMAs to and from it's main memory.

This does not simply mean to change everything from "Array-of-Structures" (AoS) to "Structure of Arrays" (SoA) like shown in the examples here. It can also mean mixing both and to *interleave* and pack data belonging to one functionality closely together, like for instance "position" and "velocity" to avoid jumping in memory for the integration of the position.

However, pure DOD systems are very hard to implement, as each pointer access is a *violation* of that *pure* concept, as you don't access a continious memory block anymore, but doing random memory accesses by dereferencing a pointer. This is particularily important for writing code for the SPU when moving for instance a particle system from the CPU to the SPU, but in the normal daily game development it is not important. It's a way to optimize sub-functionality, not to write games with it (yet, as Noels article explains).

Mike Acton from Insomniac Games has a lot of intesting material related to this topic, you can find some of his stuff here as well as Noel's articles, both highly recommended.

# Answer
> 0 votes
I have been searching for a good example of this aswell, but with limited resouces on the net and no one to tell me how to do it properly, i did it with the following implementation. (it might not be the best, but it follows the basic idea)

```
Object
   //Basic data
   Vector3* Position;
   Vector3* Rotation;
   Vector3* Scale;

Car : Object
    float* acceleration;
    Object* GetObjectData();
    //invoke the updateCars, to update all cars.
    void    UpdateCar() { UpdateCars(Postion, Rotation, Scale);

    //Update all your objects in a big loop.
    void    UpdateCars(vector3* Position, vector3* Rotation, Vector3* scale);

```

So the implementation is more or less like this : You have an base object class, which holds all common data. When your car class get constructed, you specify what amount of data you want to pool up, and therefor have enough memory for all the objects.

from there you can offcourse add identifiers or what ever feels nessecary for your implementation. but i tried this on a simpler game, and it workt pretty neat.

It´s not that far away from your design either, and frankly i dont know any more efficent way to do this.

---
Tags: c++, game-design, dod, data-oriented
---


# Question
Title: What level editor is Phil Fish using in Indie Game: The Movie?
Does anyone know what program Phil Fish is using to edit models of levels? Or is it it something he built himself? I'm new to game development and was looking for something to design levels with besides my notebook.

# Answer
> 13 votes
*"Bedard and Fish created their own editor for Fez, called the Fezzer"* (Source)

If you need a simple 2D tile editor, Tiled is a choice that works for me. There are many others available, some tile-based and some not. A couple more examples are Ogmo and Gleed2D. Note that all they do is create data - you still need some code in your game to make sense of the data, which may or may not be already written and available.

---
Tags: tools, level-design
---


title: "Super meatboy"-ish replay

text:
# Question
Title: "Super meatboy"-ish replay
I'm making a platformer built from mini-levels - and I want to create a sort of a replay of all the player tries that the player did for the level.

My question is - what is the best way to record the player's actions in-game, so that I could replay them later when he finishes the level.

I thought about recording only the player's input and replay them later on, each on a clone of the player. The problem I have with this is with dynamic obstacles (that could be moved around) - if one clone moves them, it throws the simulation off for the rest of the clones.

So then I thought about recording every frame the X/Y of the player, and then just replay it - but that seems it could cause a major memory leak and very ineffective.

So - does anyone have any ideas? :)

**EDIT:** As per the request in the comment, link showing said mechanic

# Answer
I'm not sure why don't you save player position (and maybe it's animation) for every frame, let's do a little bit calculations: each player position is combined of two floating point numbers (aka. 8 bytes), you also need to know which animation the character was showing at that frame and exactly how much which frame of the animation was shown in that specific time (aka. another 8 bytes). I can't think of anything else, but let's assume we need another 8 bytes for reserve. it means total 24 bytes per snapshot.

Now if you are talking about SMB most runs won't be longer than 5 minutes, meaning 300 seconds or 18k frames (60 fps). If you want to show a replay exactly as shown in the first play, you need to store all those 60 frames per second, based on what we calculated before you'll need 18k * 24bytes memory per try (meaning 432kb). If your target market is PC, you won't have any problems storing even 100 replications (43MB) which is even more than what SMB showed after you've finished level.

Now let's see how can we optimize our data storage system to consume less memory:

1. you really don't need 8 bytes of floating point number for position. Usually you can compress all those data into 3 or 4 bytes of fixed point numbers.
2. you don't need 8 bytes for animation either, you normally don't have more than 256 different animations for your main character, and non of your animations contain more than 256 different frames, so you can store all the data in 2 bytes at most.
3. I've put 8 bytes for reserve, so I will expect you to use those 8 bytes wisely (reduce them as much as you can!)
4. you don't need to save replay at 60fps either, you can easily save 20fps and interpolate all the frames between them. I'm pretty sure user won't notice any difference.
5. since you are suggesting your game consist of mini-levels I think 5 minutes is really more than a normal run in your game, though I won't reduce that either!

Now let's see how much data we need for this new replay system (4 + 2 + 8) * 20 * 5 * 60 = 84kb per replication, which means you can easily show up to 100 replications in any iOS /Android device!

Do you need to save even more memory? You can try storing only key frames with their time and interpolate all the frames between them. key frames simply mean the frames where player's Velocity changed due to any reason (hitting obstacles, user input change, ...) but it'll result in consuming much more processing power while showing those replays.
> 3 votes

# Answer
In the case of something simple like Super Meatboy you could try and log all the input and replay it. Just make sure it's a high enough resolution.

If you want to do anything advanced it's a good idea to look at abandoning basic data types.

For example you can create your own 'property' class. This class can do things such as log changes in it's value over time (such as in this case).

Other features are Network replication. A unique identifier (useful for network replication). Serialization (also useful for network replication and saving). Mark areas of memory as being changed since last game load (allows for almost instant saving/loading). You could also do things like reflection (ie give the property a name, get a list at runtime of all the properties). Script binding and so on.
> 0 votes

---
Tags: physics, platformer, replays
---


# Question
Title: How to eliminate screen jitter in Flash game?
We made a flash game with a big screen size(1000x600), and the terrain graphic will jitter while the screen scrolling(that's, camera moving with player) continuously.

What's the root cause? Or if you know how to eliminate this problem, please tell me. Any help is appreciated.

UPDATE:

The map's size is more bigger than screen, e.g 6000x1200. And the map has more than one layer, generally it has 3 layers. Terrain is composed by tiles. And FPS is 24.

If the FPS is set to 60, things will be better. But any way, it should work well at 24 FPS. I'm not sure if it is a natural problem of flash player, because some times a terrain object(e.g a house) look like a little bit distorted.

# Answer
> 3 votes
Thanks for your answers, I just find some articles related to this problem :

# Answer
> 3 votes
Depending of the kind of Jitter you are getting, this could be the large images snapping to pixels when they move. This will be most noticeable when it is moving slowly.

Try turning smoothing on for your bitmaps, and/or turn cache and bitmap on.

# Answer
> 1 votes
This sounds like a VSYNC issue.

https://stackoverflow.com/questions/989471/vsync-in-flex-flash-as3

This may also be worth a browse, but without more details it's really not possible to provide better information.

http://www.craftymind.com/2008/04/18/updated-elastic-racetrack-for-flash-9-and-avm2/

# Answer
> 1 votes
The thread is a little old but I decided to post my answer anyway.

A strange effect that solved my main jitter issues: Make sure you set your animated MovieClips content to even pixel coordinates!

In my case it was a simple centering that caused major jittering issues:

```
var bitmap:Bitmap = new Bitmap();
bitmap.bitmapData = bitmapData;
bitmap.smoothing = true;
bitmap.x = -(bitmap.width/2);
bitmap.y = -(bitmap.height/2);
this.addChild(bitmap);

```

Changing the following lines solved the issue:

```
bitmap.x = -int(bitmap.width/2);
bitmap.y = -int(bitmap.height/2);

```

Believe me, this caused some major headaches. I tried it both for vector graphics and smoothed Bitmaps, same effect!

---
Tags: flash
---


# Question
Title: Should I use OpenGL while working with C++?
I am completely new to programming and game development for that matter. I am using the C++ software to create my Game Engine with the help of a beginners guide. I noticed it has a OpenGL option when starting up a new project. I've heard of OpenGL pertaining to game development, not sure what it is though.

Should I be using OpenGL when creating my Game Engine? Will it matter if I just start with a blank slate?

# Answer
Yes. You should use everything you can that's pre-made. Even when you're making something very advanced you'll still use OpenGL. OpenGL is how you'll interface with the graphics hardware. It's critical.
> 6 votes

# Answer
OpenGL is a library to perform 2d and 3d graphic operations on the video card. It's useful for creating high-performance graphic engines. Its direct competitor is DirectX, which does the same and some more stuff (like audio and input), but is only supported on Windows. Asking which one is better is a great way to ignite a flamewar in any game programming community.

OpenGL is fast and powerful, but also very complicated. When you are a total beginner at programming, it is likely much too advanced for you. You should rather use a more user-friendly library for now to do graphic output, like SDL or SFML.
> 4 votes

# Answer
If you'd like to make your life twice as hard as it is already in learning C++, then bring OpenGL into the mix as well... at the very least this applies if you are using modern, shaders-based (AKA "programmable pipeline") OpenGL eg. OpenGL 2, 3 or 4.

Even with OpenGL 1.0, it is *easier* but by no means a simple matter to learn OpenGL. So you should address your learning of C++ first and once you are more comfortable with the language -- which usually will take at the very least a couple of months to gain some small degree of proficiency -- and only then start looking into how OpenGL operates.

Depending on what sort of game you are writing (2D or 3D, as well as complex vs non-complex graphical effects), you may or may *not* need what OpenGL provides. For instance, SDL, Allegro or similar 2D C++ libraries may be vastly better suited to what you are trying to do. In some cases, even where you do need 3D, there are wrapper libraries that it make it much easier for you to do that work, than using OpenGL directly.

So no, under most circumstances, absolutely do *not* jump into OpenGL at the same time as you are learning C++. Get the language basics under your belt first, and make use of easy-to-use graphics libraries to start with. You can always replace your rendering code with pure OpenGL later -- *if* you need to.
> 2 votes

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