# How to detect collision with non-rectangular objects in 2D games?

Detecting collision with rectangular objects is quite easy. I am able to write simple tile based games. Now I want to learn to write non-tile based games in which objects may not be rectangular, for example, a mountain.

Suppose I want an uneven terrain with hills and mountains how do I store the shape of the terrain? Also how do I detect the collisions for such uneven objects?

You can do it several ways:

One of which is to use a rough collision test using bounding box collision (similar to what you've been doing) then if that passes, perform a fine collision test using pixel perfect detection.

Another can be to use bounding shapes but only have them surround the area that you want to be collide-able, i.e. a hitbox, and perform intersection detection.

• How to perform a fine collision test using pixel perfect detection? – Cracker Oct 6 '11 at 14:48

Shape of terrain is usually stored as array, so called "heightmap":

height[X][Y]


You can smooth or create some fractal details on it (usually when dimensions of array are small).

Don't do collisions by hand, You might run into problems with speed, penetrations ...

Use Box2D convex polygons for sidescrollers (Scorched Earth). For topdown RPG like games ODE, Havok, Newton, Bullet ... seem to have support for heightmaps, sometimes even natively.