Hexmap Coordinates the Easy Way
When it comes to turn-based strategy games, I’ve long preferred hexes over a square grid. Naturally in working on my own projects I want to use hexes… but at first glance it seems the coordinate system for hexes must be much more complicated.
It’s actually easier than you’d think, I’ll show you how.
Hexmap Coordinate System
Determining coordinates for spaces in a hexagonal grid is relatively easy if you make a slight departure from Cartesian coordinates and slant one axis along the hex diagonal.
This neatly describes the hexes without needing additional work to accommodate the “staggered” rows that a strict Cartesian system would require.
Hex Movement Transforms
When moving a unit to a new hex using this system the coordinate transforms are pretty simple. Here, I’ll get you started:
Move N: y + 1
Move NE: x + 1, y + 1
Move SE: x + 1
I’m sure you can figure out the other three transforms.
Calculating Hex Distance
Distance in hexes from one hex to another is also reasonably simple to determine with this system.
Assuming there are no obstacles forcing an inefficient path (you are determining “straight line” distance) the calculation described by Stefano MacGregor is just what’s needed. I’ll paraphrase:
Distance is equal to the greatest of the absolute values of: the difference along the x-axis, the difference along the y-axis, or the difference of these two differences.
For example, from (1, 1) to (0, 3):
Δx = 0 - 1 = -1
Δy = 3 - 1 = 2
Δd = 2 - (-1) = 3 (greater than |2| or |-1|)
D = |3| = 3
-there’s a distance of three hexes.
Pretty easy. Now to convert between pixel coordinates on screen to this hex coordinate system is beyond the scope of this post… I may blog about that later, but in the meantime you could check out other articles on the topic such as Amit Patel’s take.