1. Stay inside, detect a hit
Two ideas power almost every 2D game:
- Clamping keeps a value inside limits, so the player can’t leave the screen:
Math.min(Math.max(value, min), max) - Collision (overlap) of two rectangles
aandb, each with x, y, w (width), h (height). They overlap when all four are true:
a.x < b.x + b.w(a starts before b ends, left-right)a.x + a.w > b.x(a ends after b starts)a.y < b.y + b.handa.y + a.h > b.y(same idea, up-down)
Keep these as small pure functions: same inputs → same answer, easy to test.
const clampDemo = (v, lo, hi) => Math.min(Math.max(v, lo), hi);
console.log(clampDemo(-30, 0, 260)); // 0
console.log(clampDemo(120, 0, 260)); // 120
console.log(clampDemo(400, 0, 260)); // 260
Challenge: clamp and overlaps
Complete two pure functions:
clamp(value, min, max)returns value, but never less thanminor more thanmaxoverlaps(a, b)returnstruewhen rectanglesaandb(each{ x, y, w, h }) overlap. Rectangles that only touch at an edge do not overlap.