The Allegro Wiki is migrating to github at

Bounding Box

From Allegro Wiki
Revision as of 19:01, March 14, 2008 by CGamesPlay (talk | contribs) (recat)
Jump to: navigation, search


While not the fastest method of collision detection (and not technically even a method for collision detection), Bounding Box (BB) is often a favourite among many developers. Put simply, this technique involves checking whether an object has intercepted (overlapped) an invisible square boundary that is usually placed over, and often remains relative to, a game object.

An illustration of a Bounding Box -> Bounding Box collision check

As a BB consists of four sides (making a square), a BB collision routine needs four values for each BB involved: a location vector (the x and y position of the BB object), as well as the BB's height (h) and width (w). Using these four values we can calculate:

  • The location of the top-left corner of the BB (x, y)
  • The location of the top-right corner of the BB (x + w, y)
  • The location of the bottom-left corner of the BB (x, y + h)
  • The location of the bottom-right corner of the BB (x + w, y + h)


Here's code to check for a collision between two bounding boxes. Essentially all that is happening here is we are running four checks to make sure b1 and b2 are not overlapping in any way. If any of these checks fail, we know that b1 and b2 are, in fact, overlapping.

<highlightSyntax language="c"> int bounding_box_collision ( int b1_x, int b1_y, int b1_w, int b1_h, int b2_x, int b2_y, int b2_w, int b2_h ) {

   if ( ( b1_x > b2_x + b2_w - 1 )  ||  // is b1 on the right side of b2?
               ( b1_y > b2_y + b2_h - 1 )       ||  // is b1 under b2?
               ( b2_x > b1_x + b1_w - 1 )       ||  // is b2 on the right side of b1?
               ( b2_y > b1_y + b1_h - 1 ) )         // is b2 under b1?
       // no collision
       return 0;
   // collision
   return 1;

} </highlightSyntax>


While the BB method works nicely for some objects, others may be problematic

The Bounding Box method is fairly simple. As such, there are very few issues or complications with its usage.

  • Bounding Boxes do exactly what they say on the tin. The problem here is, if you are trying to check collisions against a particularly complex object (one that has an obscure shape), BB may not be the method for you. Notice the diagram to the right. Now, if you consider that BB's are typically invisible to the end-user, it is possible that some objects within your game will detect collisions with other objects seemingly before they occur! One solution to this problem is to simply reduce the size of the bounding box so that it fits within your object.