Game loop, input and physics · 5 MIN READ

A spatial hash for the broad phase: bucket by cell, query neighbors, check each pair once

Build a uniform-grid spatial hash, insert objects by bounding box, query neighbors with deduplication, and count pair checks against the naive all-pairs loop.

Checking every object against every other costs n(n-1)/2 tests: 124,750 for 500 objects, every tick, and almost all of those pairs are far apart. A broad phase discards distant pairs cheaply so the exact tests from the collision lesson run only on near candidates. A uniform grid stored in a hash map is the simplest broad phase that works well for most 2D games.

gamedev · A MAP OF THE IDEA

  1. Choose a cell size
  2. Insert by bounding box
  3. Query cells, dedupe
  4. Check pairs with j > i

Useful when

  • Cuts pair checks from quadratic to near linear in spread-out scenes.
  • Simple to rebuild every tick and to verify against the naive loop.

Watch out

  • Map iteration order is random; never derive pair order from it.
  • Clustered scenes and poor cell sizes degrade toward naive cost.

Implementation & operation cost: A map or dense array rebuilt every tick plus a mark slice; memory grows with objects times cells touched.

01

Cells, keys and the truncation trap

A spatial hash divides the plane into square cells of one size and maps each cell coordinate to the objects touching it. The key is the pair floor(x / size), floor(y / size). Floor matters: converting with int() truncates toward zero, so both -0.5 and 0.5 land in cell 0, the cell at the origin becomes twice as wide as the others, and collisions near negative coordinates start to misbehave in ways that are hard to reproduce. A struct of two ints is a perfectly good Go map key; packing the pair into a uint64 saves a little hashing at the cost of clarity. Choose the cell size from your objects: around the size of a typical object, and at least the largest diameter if every object should touch at most two cells per axis.

02

Insert by bounds, query with a stamp, count the work

The program builds a seeded scene of 500 circles with radii between 2 and 8 in an 800 by 600 world. Insert files each object under every cell its bounding box touches. Query walks the cells under a box and returns each object found there exactly once: an object spanning two cells sits in both buckets, so the grid keeps a mark per object and a stamp that increases with every query, which deduplicates without allocating a set. Pair finding queries each object's own bounds and keeps only candidates with a higher index, so every unordered pair is checked once, from its lower-indexed object. The naive loop runs as well, and the two lists of overlapping pairs are compared.

go
package main

import (
	"cmp"
	"fmt"
	"math"
	"math/rand/v2"
	"slices"
)

type Circle struct{ X, Y, R float64 }

func overlap(a, b Circle) bool {
	dx, dy, rr := a.X-b.X, a.Y-b.Y, a.R+b.R
	return dx*dx+dy*dy < rr*rr
}

type cell struct{ X, Y int }

// Grid is a spatial hash: a map from cell coordinates to object indices.
type Grid struct {
	size  float64
	cells map[cell][]int
	mark  []uint32 // mark[i] == stamp: object i already returned by this query
	stamp uint32
	Seen  int // bucket entries read, duplicates included
}

func NewGrid(size float64, objects int) *Grid {
	return &Grid{size: size, cells: map[cell][]int{}, mark: make([]uint32, objects)}
}

// key uses Floor so that -0.5 lands in cell -1, not cell 0.
func (g *Grid) key(x, y float64) cell {
	return cell{int(math.Floor(x / g.size)), int(math.Floor(y / g.size))}
}

// Insert files object i under every cell its bounding box touches.
func (g *Grid) Insert(i int, c Circle) {
	lo, hi := g.key(c.X-c.R, c.Y-c.R), g.key(c.X+c.R, c.Y+c.R)
	for y := lo.Y; y <= hi.Y; y++ {
		for x := lo.X; x <= hi.X; x++ {
			g.cells[cell{x, y}] = append(g.cells[cell{x, y}], i)
		}
	}
}

// Query appends each object filed in a cell touched by the box, once.
func (g *Grid) Query(dst []int, x0, y0, x1, y1 float64) []int {
	g.stamp++
	lo, hi := g.key(x0, y0), g.key(x1, y1)
	for y := lo.Y; y <= hi.Y; y++ {
		for x := lo.X; x <= hi.X; x++ {
			for _, j := range g.cells[cell{x, y}] {
				g.Seen++
				if g.mark[j] != g.stamp {
					g.mark[j] = g.stamp
					dst = append(dst, j)
				}
			}
		}
	}
	return dst
}

type pair struct{ A, B int }

func main() {
	const n, width, height, maxR = 500, 800.0, 600.0, 8.0
	rng := rand.New(rand.NewPCG(2026, 11)) // fixed seeds: same scene every run
	objs := make([]Circle, n)
	for i := range objs {
		objs[i] = Circle{rng.Float64() * width, rng.Float64() * height, 2 + rng.Float64()*(maxR-2)}
	}

	naiveChecks, naive := 0, []pair{}
	for i := range objs {
		for j := i + 1; j < n; j++ {
			naiveChecks++
			if overlap(objs[i], objs[j]) {
				naive = append(naive, pair{i, j})
			}
		}
	}

	g := NewGrid(2*maxR, n) // cell edge = largest diameter
	for i, c := range objs {
		g.Insert(i, c)
	}
	gridChecks, found, cands := 0, []pair{}, []int{}
	for i, c := range objs {
		cands = g.Query(cands[:0], c.X-c.R, c.Y-c.R, c.X+c.R, c.Y+c.R)
		for _, j := range cands {
			if j <= i { // self, or a pair already handled from j's side
				continue
			}
			gridChecks++
			if overlap(c, objs[j]) {
				found = append(found, pair{i, j})
			}
		}
	}
	slices.SortFunc(found, func(p, q pair) int {
		return cmp.Or(cmp.Compare(p.A, q.A), cmp.Compare(p.B, q.B))
	})

	fmt.Printf("%d circles, %d occupied cells of %.0f units\n", n, len(g.cells), g.size)
	fmt.Printf("naive: %d pair checks, %d overlaps\n", naiveChecks, len(naive))
	fmt.Printf("grid: %d bucket reads, %d pair checks, %d overlaps\n", g.Seen, gridChecks, len(found))
	fmt.Printf("same pairs: %t, first %v\n", slices.Equal(naive, found), found[0])

	blast := Circle{400, 300, 40}
	near := g.Query(nil, blast.X-blast.R, blast.Y-blast.R, blast.X+blast.R, blast.Y+blast.R)
	hits := 0
	for _, j := range near {
		if overlap(blast, objs[j]) {
			hits++
		}
	}
	fmt.Printf("blast r=%.0f: %d candidates, %d hit\n", blast.R, len(near), hits)
}
Read the code

rand.NewPCG(2026, 11) fixes the scene, so the numbers repeat on every run with this toolchain. The naive loop makes 124,750 checks and finds 90 overlaps. The grid reads 2,254 bucket entries, counting duplicates and each object's own entry, and runs only 330 exact checks to find the same 90 pairs; slices.Equal confirms that the sorted lists match. The last query models an explosion of radius 40 at the center of the world: 7 objects are candidates and 4 of them actually intersect the blast.

03

Two kinds of duplicates and one ordering trap

A broad phase produces two different duplicates. The first is one object found in several cells during a single query; the stamp removes it. The second is the pair (i, j) found once from i and again from j; the j > i rule removes it, and also drops the object itself, which every query returns. Miss either and overlaps are reported twice, so collision responses apply twice and objects bounce with double force. Ordering is the subtler issue. Iteration over a Go map is deliberately randomized, so a broad phase that produces pairs by ranging over the cell map yields a different pair order on every run; any resolution that moves objects then depends on that order, and the simulation stops being reproducible. This program never ranges over the map: it walks objects by index and reads cells by key, and it sorts the final list anyway before comparing.

04

Grids in production: rebuild, reuse, tune

Most games rebuild the grid every tick, because moving objects change cells and incremental updates add bookkeeping that rarely pays off. A fresh map every tick allocates; resetting each bucket to length zero keeps the backing arrays but also keeps keys for cells nobody occupies any more, so clear the map now and then. For a bounded world, a dense grid indexed by row*cols + col avoids hashing entirely and keeps memory predictable. Tune the cell size by measurement: too small and large objects touch many cells, too large and buckets fill until the grid degenerates toward the naive loop. Heavily clustered scenes, such as a crowd packed into one room, defeat any uniform grid; quadtrees or sort-and-sweep along one axis handle those better.

go
// DenseGrid covers a bounded world; buckets are reused every tick.
type DenseGrid struct {
	cols, rows int
	size       float64
	buckets    [][]int // index: row*cols + col
}

func (g *DenseGrid) Reset() {
	for i := range g.buckets {
		g.buckets[i] = g.buckets[i][:0] // keep capacity for the next tick
	}
}

func (g *DenseGrid) cell(x, y float64) int {
	col := min(max(int(math.Floor(x/g.size)), 0), g.cols-1)
	row := min(max(int(math.Floor(y/g.size)), 0), g.rows-1)
	return row*g.cols + col
}
Read the code

This fragment shows the bounded alternative to the map-based Grid and runs in your own project. Reset keeps each bucket's backing array, so after the first few ticks a rebuild allocates nothing. cell clamps coordinates into the world, which is a design decision: objects outside the bounds pile into the edge cells instead of disappearing, and the exact narrow-phase test still decides whether they collide.

05

Keep the naive loop as the oracle

The strongest test for a broad phase is the one the program already runs: on seeded scenes, the set of overlapping pairs must equal the naive result exactly. Repeat it across several seeds, densities and cell sizes, including objects larger than a cell and objects at negative coordinates, and keep it in the test suite as the oracle for every later optimization. Then benchmark on realistic scenes and record pair checks next to nanoseconds, because the counts explain the timings. A broad phase that is fast but occasionally misses a pair is the kind of bug that surfaces as a bullet passing through an enemy once a week.

TAKE THIS WITH YOU

Bucket objects into cells with floor-based keys, query only nearby cells, deduplicate with a per-query stamp and a lower-index pair rule, never derive pair order from map iteration, and keep the naive loop as the correctness oracle.

Check your understanding

In the grid pair search, every object queries its own bounds. Why does the loop skip candidates with j <= i?

Go to the source

Progress stays in this browser. No account needed.