Monday, 1 June 2015

Finding Distance on a Hexagon Grid

One problem we have to solve when we're working hex grids is to calculate the distance between two hexes.

On a square grid, there are a few ways of doing this. The most accurate method would be to apply Pythagoras' theorem to find the length of the diagonal between two squares.

But this leads to really messy numbers, so most games opt for something simpler. I've seen some where moving diagonal is simply not allowed. Others count diagonal distances as either one or two units, alternating.



On a square grid, if diagonals are disallowed, the result is a diamond pattern.


If diagonals are counted the same as orthogonal movements, the result is a square pattern.


How does this apply to a hexagon grid? Remember that each hexagonal position is described with two numbers.


In this image, consider the hexagon [0,0]. We would expect that moving from that hexagon to any of the six that border it would be a movement of one distance. However, looking at the numerical values, in only four of the six directions is the movement of one unit. To go in a north-west or south-east direction is [-1, 1] or [1, -1], respectively.

We want movements in all six directions to be counted the same. To do this, we'll need something like the square grid where diagonal moves are counted as orthogonal moves. In such a system, only the largest difference matters. If you are moving 2 squares down, and one across, then that is a distance of 2 squares.

Further more, in a peculiarity of hexagon grids, we can get accurate results by adding a third, imaginary axis. This axis is only used to calculate distance.

The Z-axis in each hex is always such that X + Y + Z = 0.

In the example above, the 4 hexes that are only one unit away from [0, 0]  would have a Z value of 1 or -1, while those that are two units away have a Z value of 0.
You can imagine this as adding height to the grid, so that some hexes are higher or lower than others. This bubbly, warping grid  corrects the distance so that [-1, 1, 0] is as far from [0, 0, 0] as [1, 0, -1] is.

As well, we apply the idea from the square grid where diagonal moves are counted the same as orthogonal moves. This way, only the greatest distance on an axis matters when calculating the distance between points.

So, to find the distance between two hexagons [X1, Y1, Z1] and [X2, Y2, Z2] on the grid, first find
the Z values, then find the maximum number between |X1 - X2|, |Y1 - Y2|, and |Z1 - Z2|.

No comments:

Post a Comment