Collision Engine
Overlap tests for boxes, circles and points, fast-object sweeps so bullets don’t pass through walls, platformer-style movement against solid boxes or tiles, collision layers, and a spatial hash for many objects.
Files: collision-engine.js (the component, no dependencies) and collision-engine.test.mjs (8 tests).
Copy collision-engine.js into your game, for example to src/components/, and import it as an ES module.
Usage
import { overlaps, moveAndCollide, createSpatialHash, canCollide, LAYERS } from "./collision-engine.js";
// platformer movement: solid boxes or a tile grid
const r = moveAndCollide(player, player.vx * dt, player.vy * dt, { solids: walls });
player.x = r.x; player.y = r.y; if (r.hitY) player.vy = 0; player.onGround = r.onGround;
// many objects: only test nearby pairs
const grid = createSpatialHash(64);
for (const e of enemies) grid.insert(e);
for (const b of bullets) for (const e of grid.query(b)) if (overlaps(b, e)) hit(b, e);
API
Shapes are plain objects: box { x, y, w, h } (x, y = top left), circle { x, y, r } (x, y = centre), point { x, y }.
overlaps(a, b)any pair of box / circle / point
boxOverlap, circleOverlap, circleBox, pointInBox, pointInCircle
penetration(a, b) → { x, y } | nullsmallest push that moves box a out of box bsweep(box, dx, dy, solid) → { time 0..1, nx, ny } | nullfirst contact while moving (stops tunnelling)moveAndCollide(box, dx, dy, { solids, tiles: { grid, size, solid(v) } }) → { x, y, hitX, hitY, onGround, hitCeiling, touched }moves along x then y, stopping at walls; a tile grid is an array of rowsraycast(x, y, dx, dy, boxes, maxDist) → { box, dist, x, y, nx, ny } | nullcreateSpatialHash(cellSize) → { insert(o), remove(o), update(o), query(shape) → Set, clear(), size }
LAYERS, canCollide(a, b) objects with layer (one bit) and mask (bits they hit)
Engines
| Engine | Notes |
|---|---|
| Vanilla, PixiJS, Three.js (2D or top-down on the ground plane) | yes. |
| Phaser | use Arcade Physics for moving bodies; these helpers still help for custom checks such as hitboxes and line of sight. |
Tests
Node tests: every shape pair, touching edges don’t count, penetration direction, sweeps at speed, ground and wall detection against boxes and tiles, raycasts, the spatial hash, layers.
Run them with node --test toolkit/components/collision-engine/ (Node 20 or newer, nothing to install).