Handle large numbers of entities efficiently by only checking things that are near each other. Uniform grids / spatial hashes for moving objects of similar size, quadtrees for uneven sizes and static worlds, cell size choice, broad phase then exact test, radius queries for AI and explosions, all-pairs collision, culling, sleeping far-away entities, and tilemap lookups. Includes a tested grid an...
Download skill (.zip) Files on GitHubGame spatial partitioning
Checking every object against every other is O(n²): 2,000 objects is 2 million checks per frame. Partitioning checks only
neighbors. Drop-in: assets/spatial.js (tested against brute force: same results; 2.2 ms vs 55 ms for 2,000 objects).
Uniform grid (default choice)
import { SpatialGrid } from "./core/spatial.js";
const grid = new SpatialGrid(64); // cell ≈ 1–2× the typical object size
// every step (rebuilding is cheap and simple):
grid.clear(); for (const e of enemies) grid.insert(e); // e = { x, y, w, h } (top-left box)
for (const b of bullets) for (const e of grid.queryRect(b.x, b.y, b.w, b.h)) if (hit(b, e)) damage(e, b);
const near = grid.queryRadius(boom.x, boom.y, 120); // explosion, AI perception, magnet pickups
grid.pairs((a, b) => separate(a, b)); // all overlapping pairs once (crowds, boids)
Quadtree (uneven sizes, mostly static)
import { Quadtree } from "./core/spatial.js";
const walls = new Quadtree({ x: 0, y: 0, w: worldW, h: worldH }, { maxItems: 8, maxDepth: 8 });
level.colliders.forEach((c) => walls.insert(c)); // build once per level
const nearby = walls.queryRect(player.x - 50, player.y - 50, 100, 100);
Choosing
| Situation | Use |
|---|---|
| Many moving objects of similar size (bullets, enemies, boids) | Grid, rebuilt every step |
| Tile-based world | No structure needed: the tilemap is a grid (tileAt(floor(x / T), floor(y / T))) |
| Static colliders with very different sizes, big sparse world | Quadtree, built once |
| A few dozen objects | Nothing: brute force is fine and simpler |
| 3D | Grid on the ground plane (x, z) for most games; three.js raycasts against a small candidate list |
Cell size: too small, and big objects land in many cells (slow inserts). Too large, and each cell holds too many (slow queries). Start at about 2× the common object size, then measure.
Also partition the work
- Culling: query the camera rectangle and draw only those objects.
- Sleeping: update far-away entities less often (every 4th step) or not at all until the player is near.
- Staggering: spread expensive AI (pathfinding, line of sight) across frames:
if ((frame + e.id) % 4 === 0) think(e).
Prove it
Profile with the heaviest scene (game-performance-profiling). Record entity count, then update time before and after: “1,500 enemies: collision 38 ms → 1.9 ms per step.”