Collision Detection

Collision detection is a way to detect a collision (crash or contact) between two game entities.

bounding-box.png

The entities are usually the currently displayed sprites (or bounding boxes of two game objects. In other cases, it may be between two "areas", such as the circle around a game object used to create a proximity mine.

An important thing to remember is that collision detection is performed two game entities at a time and no more than that. Also remember that collision detection does not cause a game object to react to a collision, only to detect that a collision has happened.

Collision Detection Types

2D

2D collision detection has several types. The most often used types of 2D collision detection are :

  • Rectangle overlap collision detection
  • Circle overlap collision detection
  • Line intersection collision detection
  • Pixel Perfect collision detection

It is used in most 2D games and surprisingly in some 3D first person shooters such as Wolfenstein 3D and Doom.

Rectangle Overlap Collision Detection

if a.x2 >= b.x1 and a.x1 <= b.x2 and a.y2 >= b.y1 and a.y1 <= b.y2 then 'collision\

Circle Overlap Collision Detection

if (a.x - b.x) ^ 2 + (a.y - b.y) ^ 2 <= (a.radius + b.radius) ^ 2 then 'collision

Line Intersection Collision Detection

w = (b.y2 - b.y1) * (a.x2 - a.x1) - (b.x2 - b.x1) * (a.y2 - a.y1)
if w = 0 then 'no intersection (parallel lines)
v = (b.x2 - b.x1) * (a.y1 - b.y1) - (b.y2 - b.y1) * (a.x1 - b.x1)
u = v / w

The intersection point is then

x = a.x1 + u * (a.x2 - a.x1)
y = a.y1 + u * (a.y2 - a.y1)

But this is for infinite lines, and you probably wanted to see if two segments intersected. This is done by checking that the intersection point lies on both of the segments.

if x < a.x1 or x > a.x2 or y < a.y1 or x > a.x2 then 'no intersection
if x < b.x1 or x > b.x2 or y < b.y1 or x > b.x2 then 'no intersection

Pixel Perfect Collision Detection

3D

2D Collision in 3D

Some 3D games use 2D collision detection even though they are rendered in 3D. Doom by Id Software is a classic example of this.

See Also

Links

Categories: Collision : Game Physics : Game Programming
page_revision: 35, last_edited: 1256956428|%e %b %Y, %H:%M %Z (%O ago)