Adding collision detection to the game framework

Adding collision detection to the game framework

Introduction

Our previous exercise enabled us to animate balls in the game framework (this example).

Now we can add the functionality presented in the last lesson, to perform collision tests between a circle and a rectangle. It will be called 60 times/s when we update the position of the balls. If there is a collision between a ball (circle) and the monster (rectangle), we set the ball color to red.

Try the example at JsBin!

Collision between balls and the monster

Source code extract:

  1. function updateBalls(delta) {
  2.    // for each ball in the array
  3.    for(var i=0; i < ballArray.length; i++) {
  4.      var ball = ballArray[i];
  5.      // 1) move the ball
  6.      ball.move();
  7.      // 2) test if the ball collides with a wall
  8.      testCollisionWithWalls(ball);
  9.      // 3) Test if the monster collides
  10.      if(circRectsOverlap(monster.x, monster.y,
  11.                          monster.width, monster.height,
  12.                         ball.x, ball.y, ball.radius)) {
  13.         //change the color of the ball
  14.         ball.color = ‘red’;
  15.      }
  16.      // 3) draw the ball
  17.      ball.draw();
  18.   }
  19. }

The only additions are: lines 13-19 in the updateBalls function, and the circRectsOverlap function!

Leave a comment