skip to content

In a uniform grid or spatial hash broad phase, how do you choose the cell size, and what goes wrong at either extreme?

level: middleimportance: should knowfreq 50%

answer

  1. bodies sharing a cell pair up
  2. match the common body size
  3. at most two cells per axis
  4. tiny cells multiply insertions
  5. huge cells bring back pairwise cost

basics

~10 s

Size grid cells near the largest common moving body so each body touches only a few cells. Too small, and bodies span many cells; too large, and crowded cells bring back the pairwise cost.

solid answer

~50 s

A grid maps a point to integer cell coordinates with `floor(x / cellSize)` per axis; each body registers in every cell its AABB touches, and candidate pairs are bodies sharing a cell. A **spatial hash** stores only occupied cells by hashing those coordinates into a fixed-size table, so the world needs no bounds and memory follows the bodies, at the price of occasional hash collisions that add false candidates. If no body is bigger than a cell on any axis, each touches at most two cells per axis, eight in 3D. Much smaller cells multiply insertions, memory and duplicate pair reports; much larger cells crowd many bodies into one cell, where every pair inside is tested. Widely mixed sizes break a single grid: keep the static level and giant bodies in another structure, or use a hierarchy of grids whose cell sizes grow by a factor such as two.

go deeper

for a junior

Recall that a grid broad phase pairs bodies sharing a cell, and that the cell size should be close to the size of a typical moving body.

for a middle

Explain the cell-size arithmetic, at most two cells per axis for a body no larger than a cell, and the difference between a dense grid and a spatial hash.

for a senior

Diagnose grid slowdowns from the scene: oversized movers, clustered heaps, duplicate pairs, and propose separate structures or a hierarchical grid.

for a principal

Decide whether a game's body mix suits a grid at all, weighing its simplicity and parallelism against its blindness to density and size variation.

## From positions to cells A **uniform grid** divides space into equal cubes of side `cellSize`. A point maps to integer cell coordinates `(floor(x / cellSize), floor(y / cellSize), floor(z / cellSize))`. A body registers in every cell between the cell of its AABB's minimum corner and the cell of its maximum corner, and two bodies become a **candidate pair** when they share at least one cell. Use `floor`, not truncation toward zero: truncation maps small negative and small positive coordinates both to cell 0, so the cells around the origin become twice as wide. ## Dense grid or spatial hash | Storage | Strength | Weakness | |---|---|---| | Dense array of cells | direct indexing, no hashing | memory for every cell, including empty ones; the world must be bounded | | Spatial hash | memory follows occupied cells; unbounded worlds | hash collisions put distant cells in one slot, adding false candidates | A common hash multiplies each integer coordinate by a different large prime, combines the results with XOR and takes the remainder by the table size. A collision is harmless for correctness: the pair's AABB test rejects it. Storing the cell coordinates with each entry lets the broad phase skip colliding cells before testing. ## Choosing the cell size The usual rule is a cell about the size of the **largest common dynamic body**, or slightly larger. The arithmetic behind it: - **Body no larger than a cell.** Its extent on each axis fits within one cell width, so it spans at most two cells per axis: at most 4 cells in 2D and 8 in 3D. - **Cells too small.** Take 0.5 m debris in 0.25 m cells: a piece can span three cells per axis, up to 27 cells in 3D, so insertion, memory and duplicate reports all grow. - **Cells too large.** Take 10 m cells for the same debris: one cell covers 1,000 cubic metres, and testing inside a cell is pairwise, `m(m-1)/2` for `m` bodies in it. - **Mixed sizes.** A moving 40 m by 10 m platform, under a metre thick, in 1 m cells spans up to 41 by 11 by 2 cells, about 900 registrations, every step it moves. Keep such bodies and the static level in a separate structure, or use a **hierarchical grid**: several grids whose cell sizes grow by a factor such as two, each body stored in the finest level whose cells fit it, and each body checking its own level and the coarser ones. ## Duplicates and the clustered worst case Two bodies that share several cells are found once per shared cell. Two common fixes: 1. Collect pairs into a set keyed by the two body ids, so duplicates collapse. 2. Report a pair only from the cell that contains the minimum corner of the two boxes' overlap region. Both bodies occupy that cell, and exactly one cell contains that corner, so each pair is reported once with no set. The **clustered worst case** is a grid's weak point: when a shattered wall leaves 500 debris pieces in one heap that fits in a cell or two, the per-cell test is `500 * 499 / 2 = 124,750` pairs, and a fixed cell size cannot adapt to the density. A tree, which subdivides where bodies crowd, degrades more gracefully there. ## Updating the grid each step - **Rebuild:** clear the cells and reinsert every dynamic body. Simple, branch-light and easy to parallelise; the cost is linear in the number of registrations. - **Incremental:** move a body between cells only when its cell range changed, which is rare for slow bodies when cells are well sized. - **Static bodies** are inserted once, or kept out of the grid entirely in a structure tuned for them. ## When a grid is the right call Grids shine with many similarly sized bodies spread fairly evenly: hundreds of projectiles in a bullet-hell arena, sparks, small debris. They lose to trees when sizes vary wildly or the world is large and sparse, and to sweep-and-prune when bodies are few and well spread. Interviewers usually want the cell-size reasoning above, the duplicate-pair fix, and the clustered case named without prompting.

  • How do you stop a pair from being reported once for every cell the two bodies share?
    Either insert pairs into a set keyed by the ordered pair of body ids, or report a pair only from the cell containing the minimum corner of the two AABBs' overlap region. Both bodies occupy that cell and exactly one cell holds the corner, so every pair comes out once without any set.
  • When would you pick a spatial hash over a dense grid?
    When the world is large or unbounded and bodies occupy a small fraction of it, such as a big level with action concentrated in a few places. A dense grid pays memory for every empty cell; a hash pays only for occupied cells, accepting rare collisions that the AABB test filters out.

  • Picks the smallest possible cell size on the theory that smaller is always more precise.
  • Thinks a hash collision can make the broad phase miss a pair.
  • Forgets that a body larger than a cell registers in many cells.
  • Reports every shared cell's pair without deduplication.
  • Uses truncation toward zero for negative coordinates without noticing the double-width cells at the origin.