Calculating distance on a hexagon grid

DeathorGlory9 picture DeathorGlory9 · Jan 24, 2013 · Viewed 16.4k times · Source

What I am trying to do is find how many hexagons are in between two points on a hex grid. I have tried searching online for a formula but I have not been able to find one that matches the type of hex grid I am using.

The hex grid is laid out like this one with the same coordinate system: http://www.gamedev.net/index.php?app=core&module=attach&section=attach&attach_rel_module=ccs&attach_id=1962

I am aware that this may not be possible with this coordinate system but this is a last ditch effort before I go back and change it. Thank you very much in advance.

Answer

user2709663 picture user2709663 · Aug 23, 2013

If you had used a coordinate system which goes along the grain of the hexes in two directions, you could have used:

distance = max(
     abs(dest.y - start.y),     
     abs(dest.x - start.x),
     abs((dest.x - dest.y)*-1 - (start.x - start.y)*-1)
)

However you didn't, you're using a squiggly coordinate system which goes with the grain along one direction only (horizontal). Luckily we can transform between the two using

straight.y = squiggle.y
straight.x = ciel(squiggle.y / -2) + squiggle.x

So, solving for distance using this system of equations gets you:

distance = max(
     abs(dest.y - start.y),     
     abs(ceil(dest.y / -2) + dest.x - ceil(start.y / -2) - start.x),
     abs(-dest.y - ceil(dest.y / -2) - dest.x + start.y  + ceil(start.y / -2) + start.x)
)

That will get you the Manhattan distance between two hexes using only their coordinates (Assuming I didn't make any typos transposing x and y, since your grid is rotated 90 degrees from mine). However you must buy a cookie for my middle school algebra teacher for it to work, otherwise I will have messed up the distributive property.

Note: May require fiddling to work with negative coordinates, I didn't check.