Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distance between 2 hexagons on hexagon grid

I have a hexagon grid:

hexagon grid

with template type coordinates T. How I can calculate distance between two hexagons?

For example:

dist((3,3), (5,5)) = 3

dist((1,2), (1,4)) = 2

like image 316
zodiac Avatar asked Apr 10 '13 07:04

zodiac


1 Answers

Posting here after I saw a blog post of mine had gotten referral traffic from another answer here. It got voted down, rightly so, because it was incorrect; but it was a mischaracterization of the solution put forth in my post.

Your 'squiggly' axis - in terms of your x coordinate being displaced every other row - is going to cause you all sorts of headaches with trying to determine distances or doing pathfinding later on, if this is for a game of some sort. Hexagon grids lend themselves to three axes naturally, and a 'squared off' grid of hexagons will optimally have some negative coordinates, which allows for simpler math around distances.

Here's a grid with (x,y) mapped out, with x increasing to the lower right, and y increasing upwards.

Hexagon grid with two coordinates and three axes overlaid

By straightening things out, the third axis becomes obvious.

Hexagon grid with three coordinates and three axes overlaid

The neat thing about this, is that the three coordinates become interlinked - the sum of all three coordinates will always be 0.

With such a consistent coordinate system, the atomic distance between any two hexes is the largest change between the three coordinates, or:

d = max( abs(x1 - x2), abs(y1 -y2), abs( (-x1 + -y1) - (-x2 + -y2) )

Pretty straightforward. But you must fix your grid first!

like image 197
keekerdc Avatar answered Sep 18 '22 18:09

keekerdc