Technical Deep-Dive Asteroid Outpost C# Quadtree Spatial Partitioning

2D Spatial Quadtree

Fast collision detection, range queries, and viewport culling across large space maps—explained from a 1D bi-tree up to a 2D quadtree.

A friend (Gary) and I implemented a spatial quadtree for rapid collision detection and viewport culling in a large 2D space (also packaged separately as the archived XNA QuadTree library). It's easiest to explain a 1D bi-tree first, then expand to a 2D quadtree.

The problem

If you have hundreds of varying-sized objects in a large 1D space, checking whether your new position collides with anyone means looping over every object: my.x + my.width > their.x && my.x < their.x + their.width hundreds of times whenever something moves.

In a space game with asteroids, ships, turrets, power ranges, and projectiles all moving and querying nearby entities every frame, brute-force checks scale poorly fast.

The solution

Store objects in a tree of nodes where each node holds a list of entities and optionally splits into 2 child nodes (left and right) once it exceeds a threshold (say, 5 entities). Entities are pushed down into whichever child completely contains them; anything straddling the boundary stays on the parent node.

type Node = {
  Entities: Entity[];
  Bounds: { Left: number; Right: number };
  Left?: Node;
  Right?: Node;
};

To check collisions, test against entities in the root node and only recurse into child nodes whose bounds overlap your query box. Entire regions of the map that don't intersect your query are skipped immediately.

Expanding to 2D

In a 2D quadtree, each node splits into 4 quadrants (NW, NE, SW, SE) checking both x and y bounds—all the rest of the logic stays the same. In Asteroid Outpost, we used the same structure for:

  • Collision & intersection checks between ships, asteroids, and projectiles.
  • Range queries for turrets finding targets and mining lasers finding nearby asteroids.
  • Viewport culling so the renderer only iterated over entities actually intersecting the camera rectangle.

Visual Debugger & Benchmarks

To make sure our subdivision rules and edge cases behaved properly—and to tune the split threshold and max depth—we built a visual debugging app and a benchmarking harness alongside the library:

Viewport culling test showing entities inside the active query box
Viewport culling test showing entities inside the active query box
Visual quad subdivision debugger displaying live tree nodes
Visual quad subdivision debugger displaying live tree nodes
Benchmarking harness built to tune subdivision thresholds and query speed
Benchmarking harness built to tune subdivision thresholds and query speed