Hex Grid Coordinates (Pointy-Topped Axial)
Master hexagonal grids and play the target-finding mini-game!
How does it work? ↓Axial Coordinates (q, r)
In a standard square grid, we use (x, y). In a hex
grid, representing the grid efficiently in memory and math requires
a bit of cleverness. The most elegant solution is Axial Coordinates (q, r) .
q (Columns): The q axis runs vertically.
Just like the X-axis in a square grid, as you move to the right,
q increases.
r (Rows): The r axis runs diagonally. In
a Pointy-Topped grid like the one above, it typically goes from top-left
to bottom-right.
The Secret Third Axis (Cube Coordinates):
If you look closely at a hex grid, you have 6 directions of movement,
not 4. Because of this, Hex grids are actually secretly 3D Cube Coordinates projected onto a 2D plane!
There is actually a third hidden axis, s. The rule for
perfectly aligned hex grids is always: q + r + s = 0.
Because s can always be calculated as -q - r, we don't need to store it in memory. This is what we call "Axial"
coordinates — it's simply Cube coordinates with the redundant s axis removed to save memory!
Why is this math so powerful?
By understanding that Hex Grids are secretly 3D cubes, we can adapt
nearly any 2D grid algorithm effortlessly!
Distance Calculation:
To find the distance between Hex A and Hex B, you simply use the 3D Manhattan
Distance formula!
distance = (abs(A.q - B.q) + abs(A.r - B.r) + abs(A.s - B.s)) /
2
Neighbors:
To find the 6 neighbors of a hex, you simply add one of the 6 unit vectors
to your current `(q, r)` position. For example, moving directly "Right"
on a Pointy-Topped grid is q + 1, r + 0.