Rectangle Collision Detection for HTML5 Games

Rectangle Rectangle collisions are another very fast collision detection method. It doesn't work for a lot of game types, but it's great for some. Space invaders for instance, is a classic game that rectangle collision detection would work very well for. Just to be clear, we're talking about oriented (rotated) rectangles. We will work on that later.

A Rectangle Collider is also fairly simple. It has a position, and a dimension, both are vector values. We'll create a Rectangle Collider class, as well as a static function in our Colliders class for detecting collisions between the two rectangles.

class cRectangleCollider implements iCollider {
 public position: cVector = new cVector();
 public dimension: cVector = new cVector(1, 1);
 public hitTest(obj: iCollider): boolean {
  if (obj.colliderType == COLLIDER.RECTANGLE) {
   return Collision.RectangleRectangle(this, <cRectangleCollider>obj);
  }
  return false;
 }
 public colliderType: COLLIDER = COLLIDER.RECTANGLE;
}


class Collision {
 public static RectangleRectangle(a: cRectangleCollider, b: cRectangleCollider): boolean {
  var xoverlap: boolean = false;
  var yoverlap: boolean = false;
  if (a.position.x <= b.position.x) {
   if (a.position.x + a.dimension.x >= b.position.x) {
    xoverlap = true;
   }
  }
  else {
   if (b.position.x + b.dimension.x >= a.position.x) {
    xoverlap = true;
   }
  }

  if (a.position.y <= b.position.y) {
   if (a.position.y + a.dimension.y >= b.position.y) {
    yoverlap = true;
   }
  }
  else {
   if (b.position.y + b.dimension.y >= a.position.y) {
    yoverlap = true;
   }
  }

  if (xoverlap == true && yoverlap == true) {
   return true;
  }

  return false;
 }

 public static CircleCircle(a: cCircleCollider, b: cCircleCollider): boolean {
  var _tempVector: cVector = a.position.duplicate();
  _tempVector.subtract(b.position);
  if (_tempVector.magSq() <= (a.radius + b.radius) * (a.radius + b.radius)) {
   return true;
  }
  return false;
 }

}


The algorithm is pretty simple. It's looking for an overlap along the X axis and the Y axis. If there is overlap along both those axes, then there is a collision, if not the rectangles don't collide.

I've added some code to test it. It's similar to what I added to testing the circle colliders. Check out the full source code. To test the rectangle collisions, repeatedly hit the space bar. The rectangles will change randomly and appear red when there is a collision and blue when there is not.

Check out the full rectangle collision detection source code.

Next -> Part 3 - Line line collision detection

Part 4 - Oriented rectangle collision detection

Part 5 - Polygon collision detection

Part 1 - Circle circle collision detection