Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating distance on a hexagon grid

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.

like image 752
DeathorGlory9 Avatar asked Jan 23 '13 23:01

DeathorGlory9


People also ask

How do you measure distance on a hex map?

Simply counting the hexes from the grid next to your starting point to the grid where you want to stop is how you measure the distance. If a hex is 1 mile, then 5 hexes would be 5 miles. But simply moving from one hex to another would trigger the 1 mile distance.

How do you make a hexagon on a square grid?

For this example, draw a square that is five boxes long by five boxes deep. Press down lightly on the pencil when drawing the square. Darken the lines of the three middle boxes on the top and the bottom of your square. This will form the top and bottom of your hexagon.


1 Answers

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.

like image 170
user2709663 Avatar answered Sep 21 '22 12:09

user2709663