skip to content

For gameplay queries such as all enemies within a radius in a large world, when do you choose a uniform grid, a quadtree or a loose octree?

level: seniorimportance: should knowfreq 50%

answer

  1. how objects move vs how they cluster
  2. cell size tied to query radius
  3. straddling a split line
  4. size picks depth, centre picks node

basics

~20 s

A uniform grid or spatial hash with cells sized to the usual query radius suits many moving objects spread fairly evenly; a quadtree adapts to very uneven density; a loose octree handles moving objects of very different sizes in full 3D without straddling.

solid answer

~50 s

Start from the access pattern: how many objects move per frame, how evenly they spread, how much their sizes vary and how big the queries are. A **uniform grid** has constant-time updates — recompute the cell from the position, relink only on change — and a radius query visits the cells overlapping the query's bounds (at most 3 × 3 in 2D with cells as wide as the radius), then does an exact squared-distance test. It degrades when crowds pack one cell, and a **spatial hash** avoids wasting memory on a sparse world. A **quadtree** adapts to uneven density, but moving objects need reinsertion, and a classic tree strands objects straddling a split line in large nodes. A **loose octree** enlarges nodes, commonly to twice their side, so size picks the depth and the centre picks the node: constant-time insertion and no straddling, paid for by queries visiting more nodes.

code

pseudocode · 13 lines
pseudocode
function queryRadius(center, r):
    result = []
    minCx = floor((center.x - r) / s)
    maxCx = floor((center.x + r) / s)
    minCz = floor((center.z - r) / s)
    maxCz = floor((center.z + r) / s)
    for cx in minCx .. maxCx:
        for cz in minCz .. maxCz:
            for obj in cellList(cx, cz):
                d = obj.position - center
                if d.x * d.x + d.z * d.z <= r * r:
                    result.append(obj)
    return result

go deeper

for a junior

Recall that spatial partitioning avoids testing every object for a query, and name the uniform grid, the quadtree and the octree.

for a middle

Explain grid insertion and radius queries, why cell size relative to the query radius matters, and why a classic quadtree strands straddling objects in large nodes.

for a senior

Pick a structure from measured move counts, query counts, density and size variation, and justify the cell size or looseness factor with the arithmetic.

for a principal

Decide whether gameplay shares the physics spatial structure or owns its own, weighing duplicated update cost against coupling gameplay queries to the physics update schedule.

## What these queries are Gameplay constantly asks spatial questions: which enemies are within 20 metres of an explosion, which pickups are near the player, which guards can hear a noise, which interactable is closest to the cursor. These **general spatial queries** return a set of objects for gameplay code to act on. They are a different job from the physics broad phase, which shortlists colliding pairs, and from visibility culling, which decides what to draw; those are covered with collision and rendering. Some engines let gameplay reuse the physics structure for overlap queries, but the choice below is about structures built for gameplay's own access pattern. The questions that decide the structure: - How many objects **move** every frame, and how far? - How **evenly** are they spread — open fields, or crowds in a town square? - How much do object **sizes** vary — rats and dragons in the same structure? - How large are the **queries**, and do they vary? - Is the world effectively **2D** (most open worlds) or truly 3D (space games, tall vertical cities)? ## Uniform grid and spatial hash A **uniform grid** divides the world into equal square cells; each cell holds a list of the objects whose position falls in it. 1. **Insert or move**: compute the cell as `floor(x / s), floor(z / s)` for cell side `s`; if it differs from the stored cell, unlink from the old list and link into the new one. Constant time. 2. **Query** a circle of radius `r`: compute the range of cells overlapping the circle's bounding square, visit each, and keep objects whose squared distance to the centre is at most `r * r`. Cell size is the main tuning knob. An interval of length `2r` overlaps at most `ceil(2r / s) + 1` cells per axis, so with `s = r` a query touches at most 3 × 3 cells (an area of `9 r^2` scanned for a circle of about `3.14 r^2`); with `s = 2r` it touches at most 2 × 2 cells, but each holds four times the area, so `16 r^2` is scanned. Cells much smaller than the radius mean visiting many empty cells. Two weaknesses remain: - **Clustering**: if 500 units crowd one cell, every query near them scans 500 entries. - **Sparse worlds**: a dense array over a 16 km world wastes memory on empty cells. A **spatial hash** stores only occupied cells in a hash table keyed by cell coordinates; distinct cells that collide in one bucket are filtered by the exact distance test anyway. ## Quadtree A **quadtree** recursively splits a square region into four children when a node holds too many objects, so crowded areas get small nodes and empty areas stay coarse. A query descends only into nodes whose bounds intersect the query. Its costs: - **Moving objects** must be removed and reinserted, and crowds that drift trigger repeated splits and merges. - **Straddling**: in a classic quadtree an object that overlaps a split line cannot fit inside one child, so it stays in the parent node. Small objects lying on the root's centre lines stay in the root and are tested by every query, wherever it is. Storing a straddling object in several children instead requires deduplicating query results. The octree is the same idea in 3D, splitting into eight children. ## Loose octree A **loose octree** fixes straddling by enlarging every node's bounds. With a looseness factor of 2, a node whose cell has side `L` accepts objects within a box of side `2L` centred on the same point, extending `L / 2` beyond each face. An object whose centre lies in the cell fits whenever its half-extent is at most `L / 2`, so: 1. the object's **size picks the depth** — the deepest level whose `L` is at least the object's size; 2. its **centre picks the node** at that depth by simple division. Insertion and movement become constant-time arithmetic, with no boundary tests and no stranded objects. The price is paid at query time: loose bounds overlap their neighbours', so a query visits more nodes than in a tight tree. ## Choosing | Structure | Insert / move | Query | Uneven density | Mixed sizes | |---|---|---|---|---| | Uniform grid / spatial hash | constant | cells overlapping the query | degrades in crowds | large objects span many cells | | Quadtree / octree | reinsertion, split and merge churn | descends intersecting nodes | adapts well | straddlers stranded high | | Loose quadtree / octree | constant | more nodes than a tight tree | adapts well | handled by depth | For thousands of similarly sized enemies spread over a nearly flat open world, with queries of a known radius, a grid or spatial hash sized to that radius usually wins. For highly uneven density and varied query sizes, a quadtree. For objects of very different sizes moving in full 3D, a loose octree. ## Practical notes - **Measure** query counts and move counts per frame before choosing; the right answer depends on their ratio. - Separate structures per object category (enemies, pickups, sound emitters) keep queries from scanning irrelevant objects. - Compare **squared** distances to avoid square roots in the exact test. - On a dedicated server, iterate cells in a fixed order so query results come back in a deterministic order.

  • How would you size grid cells when query radii vary from 2 m to 50 m?
    One cell size cannot suit both: cells near 50 m make small queries scan large crowded cells, while 2 m cells make large queries visit hundreds of mostly empty cells. Common answers are two grids at different cell sizes, a hierarchical grid, or a quadtree. Measuring which radii dominate the frame tells you which side to favour.
  • Why do many open-world games use a 2D structure even though the world is 3D?
    Objects in most open worlds spread across the ground with limited height range, so a 3D partition adds levels of nodes that barely separate anything. A 2D grid or quadtree over the ground plane, followed by an exact 3D distance or height check on the candidates, is simpler and visits fewer nodes. Space games and tall vertical cities are the exceptions.

  • A quadtree always beats a grid because it adapts to the data.
  • Grid cells should be as small as possible to cut false candidates.
  • Every object in the touched cells can be returned without an exact distance test.
  • An object straddling a quadtree split line can simply be stored in one child.
  • Gameplay radius queries must always reuse the physics collision structure.