JavaScript
Collision detection
Check whether two rectangles collide with a bounding-box test.
Bounding box collision
To check whether two rectangles overlap we use the bounding box method. Each rectangle is axis-aligned (not rotated); the test is known as AABB (axis-aligned bounding box).
Two boxes overlap only if they overlap on both axes. x axis overlap: a.x < b.x + b.width and a.x + a.width > b.x. The same condition applies on the y axis. If all four conditions hold, the boxes collide.
Draw the target and show collision
We add a target object to the game; for example { x: 360, y: 80, width: 30, height: 30 }. In the draw function we first draw the target in green ("#16a34a"), then set the player's color based on hits(player, target). On collision we use red ("#dc2626"), otherwise blue ("#2563eb").
This visual feedback shows immediately that collision detection works.
Exercise Add a target and detect collision
Define target as { x: 360, y: 80, width: 30, height: 30 }. Add a hits(a, b) function that joins the four conditions with && and returns the result (a.x < b.x + b.width, a.x + a.width > b.x, a.y < b.y + b.height, a.y + a.height > b.y). Then inside draw, before the player, draw the target in green "#16a34a": ctx.fillStyle = "#16a34a" and ctx.fillRect(target.x, target.y, target.width, target.height). Set the player's color with hits(player, target) ? "#dc2626" : "#2563eb".
Show example solution
const target = { x: 360, y: 80, width: 30, height: 30 };
function hits(a, b) {
return a.x < b.x + b.width &&
a.x + a.width > b.x &&
a.y < b.y + b.height &&
a.y + a.height > b.y;
}
// add inside the draw function:
ctx.fillStyle = "#16a34a";
ctx.fillRect(target.x, target.y, target.width, target.height);
ctx.fillStyle = hits(player, target) ? "#dc2626" : "#2563eb";
Test yourself
-
Complete the collision condition
function hits(a, b) { return a.x < b.x + b.width && a.x + a.width > b.x && ____; }
Show answer
function hits(a, b) { return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y; }
-
Match the collision terms
- bounding box
- Bounding rectangle
- intersection
- Overlap
- AABB
- Axis-aligned box
- hits
- Collision check
-
Which is the overlap condition for two axis-aligned rectangles?
- a.x > b.x
- a.width < b.width
- a.y === b.y
- a.x < b.x + b.width && a.x + a.width > b.x
Show answer
a.x < b.x + b.width && a.x + a.width > b.x — Correct! These two conditions are needed for x axis overlap.
Next lesson: Project final - Mini game