Applying Collision Detection

We will be checking the bounding box around each object when we do our collision detection. A bounding box is the smallest rectangle that will encompass all four corners of a game logic object. We have created a function for this purpose:

function boundingBoxCollide(object1, object2) {

   var left1 = object1.x;
   var left2 = object2.x;
   var right1 = object1.x + object1.width;
   var right2 = object2.x + object2.width;
   var top1 = object1.y;
   var top2 = object2.y;
   var bottom1 = object1.y + object1.height;
   var bottom2 = object2.y + object2.height;

   if (bottom1 < top2) return(false);
   if (top1 > bottom2) return(false);

   if (right1 < left2) return(false);
   if (left1 > right2) return(false);



We can pass any two of our game objects into this function as long as each contains x, y, width, and height attributes. If the two objects are overlapping, the function will return true. If not, it will return false.

The checkCollision() function for Geo Blaster Basic is quite involved. The full code listing is given in Example 8-12. Rather than reprint it here, let’s examine some of the basic concepts.

One thing you will notice is the use of “labels” next to the for loop constructs. Using labels, such as in the following line, can help streamline collision detection:

rocks: for (var rockCtr=rocksLength;rockCtr>=0;rockCtr--){

We will need to loop through each of the various object types that must be checked against one another. But we do not want to check an object that was ...

Get HTML5 Canvas, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.