Bash.tv → GitHub → itch.io

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 }.

boxOverlap, circleOverlap, circleBox, pointInBox, pointInCircle

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).