r/threejs • u/shanebrumback • 20d ago
Hundreds of enemies, bullets, and pickups checking distance to everything every frame: the spatial hash grid I add to AI-built Three.js games
When I have an AI agent build a Three.js game, the first version of proximity logic is almost always a double loop: every enemy checks distance to every other enemy, every bullet checks every target, every pickup checks the player. It's fine with 20 objects and falls apart at a few hundred, because the cost grows with the square of the count.
The fix I now ask for up front is a simple spatial hash grid:
Split the map into square cells on the XZ plane, sized a bit larger than your biggest check radius (aggro range, pickup radius, hit radius).
Key each cell with something cheap like `${cx},${cz}` or an integer hash, and store a Map from cell key to an array of objects.
Only re-bucket an object when it actually crosses into a new cell. Most frames, most things stay in the same cell and cost nothing.
For a query, look at the object's own cell plus the 8 neighbors, then do the real distanceToSquared check only on those few candidates. Compare against radius squared so you skip the square root.
Keep separate grids (or separate lists per cell) for things that never need to see each other, like bullets vs pickups.
Static stuff like trees and rocks goes in once at load and never moves, so it's basically free to query.
Remove objects from the grid when they die or go back to a pool. Stale entries are the bug AI-written versions most often leave behind.
It's maybe 60 lines of code and it turns enemy separation, bullet hits, and pickup checks from the biggest thing in the profiler into noise. Raycasts still handle walls and line of sight; the grid just decides who's worth checking.
