Detect collisions in 2D games. Hitboxes vs hurtboxes, AABB, circles, circle-vs-box, rotated boxes and convex polygons (SAT), swept AABB for fast objects, ray and segment tests, grid raycasts (DDA) for line of sight and hitscan, collision layers and masks, broad phase vs narrow phase, and choosing hitbox sizes that feel fair. Includes a tested collide.js. Use when adding collisions, hitboxes, bu...
Download skill (.zip) Files on GitHubCollision detection
Drop-in: assets/collide.js (23 tests passed: edges, swept hits, rays, DDA, SAT, layers). Response (separating, sliding,
bouncing) lives in game-physics; many-object speed in game-spatial-partitioning.
| Need | Function |
|---|---|
| Boxes (most games) | aabb(a, b) with {x, y, w, h} top-left. Touching edges don’t count |
| How far to push out | aabbPenetration(a, b) → smallest-axis {x, y} |
| Round things | circles(a, b), circleContact(a, b) → normal + depth, circleRect(c, r) |
| Fast objects vs thin walls | sweptAABB(a, vx * dt, vy * dt, wall) → time of impact + normal |
| Rotated boxes, triangles | polygons(A, B) (SAT) with rectPoly(cx, cy, w, h, angle) |
| Hitscan, lasers, line of sight | rayRect, segments, raycastGrid(ox, oy, dx, dy, tile, isSolid) |
| Who can hit whom | LAYER bits + canCollide(a, b) (player bullets ignore the player, pickups ignore enemies…) |
Hitboxes that feel fair
- Player hurtbox smaller than the sprite (~60–80%): near misses feel like skill.
- Enemy and pickup hitboxes as big as the art or a bit bigger. Pickups are generous.
- Attack hitboxes exist only during the active frames of an attack (combat-system
attackPhase) and hit each target once. - Keep hitboxes in data next to the sprite (offset + size), and draw them with a debug key (game-collision-testing).
Order each step
- Move things (physics). 2. Broad phase: candidates from a spatial grid or the tilemap. 3. Narrow phase: exact tests.
- Collect results, then apply damage, pickups and removals (never mutate arrays mid-check). 5. Resolve overlaps (game-physics).
Tiles
For tile maps, don’t test against every tile: convert the box to the tile range it covers (floor(x / T) … floor((x + w) / T))
and check only those (game-physics moveAndSlide does this with substeps, so it never tunnels).
Pitfalls
- Mixing center and top-left coordinates. Pick one per shape and stick to it (this module: boxes top-left, circles center).
- Fast bullets: use
sweptAABB, a raycast, or projectile-systemsweepHit, never just “overlap at the new position”. - Checking the same pair twice (a hits b, b hits a). Use a pair rule or the grid’s
pairs(). - Rotated sprites with axis-aligned boxes: fine for most games. Switch to circles or SAT only when it visibly matters.