# Simulate 3D with 2D sprites

I was thinking about 2D games (like Starcraft), where the sprites are in two dimensions, but the objects that are "higher" in the screen are behind the other objects (I think this is obvious when you think that "higher" in the screen means "far" when simulating a 3D environment).

But, how do you do this programmatically? It is a good idea to track every movement for every object, assigning object to different layers in order to simulate movement in that axis?

Is there a better way?

Just because your game operates and is drawn mostly in two dimensions doesn't mean you have to treat it in only two dimensions. You could add a height variable, but this really isn't any different than a third dimension (probably corresponding to a Z axis in your case).

I would simply treat everything in 3D space, and track its x, y, and z coordinates. The latter (z) probably won't mean a whole lot, and most of your calculations can continue to ignore it. As a unit climbs a ramp or falls down a cliff, etc. you adjust its z coordinate.

If you take this approach, you can solve your problem by letting OpenGL (or DirectX?) do the depth testing for you (though this would mean slightly more work for the GPU). Simply turn on the depth buffer / depth testing in your rendering engine and the GPU will take care to ensure that objects will not be drawn in front of objects that are "nearer" to the camera than them.

• I do it this way, too. +1. Note however that 1) you need an orthographic projection (using glOrtho() for instance) and 2) if the sprites use a full alpha channel, for instance for anti-aliased contours, you will have to either accept a quality tradeoff caused by the blending method, or Z-sort tiles that have an alpha channel before sending them to the GPU and blitting them with disabled Z testing. – sam hocevar Apr 9 '11 at 2:35

Here's how I did it for my "Starcraft" clone:

1. Collect all visible sprites locations into array
2. Sort the array by sprites lower edge. Lower edge should be taken in map-coords (so that units standing on a very tall hill still would be above units behind the hill).
3. Render terrain ground strips along with units standing on them from top to bottom

Maybe something like a height variable that gets updated each time the object moves.

Run a basic sort algorithm and then you could loop through and draw each level.

Unfortunately in game development I have found that everything is done the hard way. If you want to manipulate something you will have to track it, there is likely a trade off in starcraft (not everything tracked to save processing) and this can improve playability

In the end though that is what being a programmer is all about.