7 min read
🎮intermediate

Collision Detection — When Game Objects Touch

Learn how games detect when objects overlap, from simple rectangle collision to the math behind hit detection.

Why Collisions Matter

Without collision detection, your game characters would pass right through walls, enemies, coins, and each other. Collision detection is how the game knows when two objects are touching or overlapping. Think about all the collisions in a game like Mario: - Mario hits a brick: the brick breaks - Mario touches a coin: the coin disappears and the score goes up - Mario lands on a platform: he stops falling - An enemy touches Mario: he loses a life Every one of those interactions requires the game to detect that two rectangles (or shapes) are overlapping.

Rectangle Collision (AABB)

javascript
// The most common collision check in 2D games:
// AABB = Axis-Aligned Bounding Box
function isColliding(rect1, rect2) {
  return (
    rect1.x < rect2.x + rect2.width &&
    rect1.x + rect1.width > rect2.x &&
    rect1.y < rect2.y + rect2.height &&
    rect1.y + rect1.height > rect2.y
  );
}

// Usage:
let player = { x: 100, y: 100, width: 40, height: 40 };
let coin = { x: 120, y: 110, width: 20, height: 20 };

if (isColliding(player, coin)) {
  score += 10;
  coin.collected = true;
}

How the Math Works

The AABB check answers one simple question: 'Are these two rectangles NOT separated?' Two rectangles are separated if: - One is completely to the LEFT of the other - One is completely to the RIGHT of the other - One is completely ABOVE the other - One is completely BELOW the other If NONE of those are true, the rectangles must be overlapping! That is what those four conditions in the code check. It is easier to check 'are they not touching?' than 'are they touching?' — and then just flip the answer.
Pro Tip

Many games use invisible 'hitboxes' that are simpler than the actual character image. A dragon sprite might be complex, but its hitbox is just a simple rectangle. This makes collision detection fast and predictable. Some fighting games actually show hitboxes in their debug mode — look up 'Street Fighter hitbox viewer' for a cool example!

Collision Playground

Build on the sprite movement code from the previous lesson. Add 5 colored 'coins' at random positions on the canvas. Use the isColliding function to detect when the player touches a coin. When they collide: remove the coin, add 10 to a score variable, and display the score on screen. Bonus: spawn a new coin at a random position whenever one is collected!

Ready to build?

Put what you learned into practice — pick a project and start coding.

Start Building Free