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
Rectangle Collision (AABB)
// 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
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!
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