Repeat Unit

Hexagonal grids and three coordinates

Square grids get two coordinates for free. Hexagon grids are happier with three that always add up to zero.

The usual way to store a hexagon map is in rows and columns with every other row shifted by half a cell. That works for storage and makes everything else awkward: the neighbours of a cell depend on whether its row is odd or even.

A cleaner choice uses three coordinates q, r, s along the three directions of the grid, with the rule q + r + s = 0. Think of the hexagons as the diagonal slice through a stack of cubes, which is where the name cube coordinates comes from.

A map of radius two, every cell labelled q, r, s
A map of radius two, every cell labelled q, r, s. The coordinates always sum to zero.
  • Neighbours are the six permutations of (+1, −1, 0) added to a cell.
  • Distance between two cells is max(|Δq|, |Δr|, |Δs|), which equals (|Δq| + |Δr| + |Δs|)/2.
  • Counting: a hexagonal map of radius N has 3N(N + 1) + 1 cells: 1, 7, 19, 37, …
  • Rotation by 60° about the centre is a cyclic shift with a sign change: (q, r, s) → (−r, −s, −q).

Since s is always −q − r, only two numbers need to be stored (axial coordinates), and the third is recovered when it is useful. Converting a cell to a point on the screen is a fixed linear map; flat-topped and pointy-topped grids differ only in that map, and everything above stays the same.