Friday, 20 April 2012

Quick and easy collision detection


This is a neat little trick I found a few months ago, which I thought was worth documenting.

If you're making a 2D sprite based game and want a quick and easy way to do collision detection between the player sprite and the enemy sprites, you can use an OpenGL occlusion query.

First of all, start an occlusion query, draw the player's sprite into an empty buffer, then end the query. The result will give you the total number of pixels in the sprite. Then, on every frame:

  1. Draw all the enemy sprites at the same depth.
  2. Start the occlusion query.
  3. Draw the player sprite behind the enemy sprites.
  4. End the query and get the result.
If the number of pixels drawn from the player is less than the total, they've collided with an enemy.

The beauty of this is that it's pixel-accurate and essentially zero cost. The downside is that occlusion query support isn't available in OpenGL ES or WebGL yet, so it won't work there.

No comments:

Post a Comment