# Re: Calculating distance using hex coordinate system

*From*: me@xxxxxxxxxxx*Date*: Mon, 17 Sep 2007 20:46:41 GMT

Torben, that did the trick! Thank you very much for your assistance!

On Mon, 17 Sep 2007 12:15:24 +0200, torbenm@xxxxxxxxxxxxx (Torben

Ægidius Mogensen) wrote:

me@xxxxxxxxxxx writes:.

Howdy all,

I've created a hex grid bitmap, and have assigned each hex a

coordinate exactly as portrayed on this page,

http://www.gamedev.net/reference/articles/article1800.asp and am now

trying to nail down the algorithm to determine the distance between

any two hexes when the coordinates are known.

I prefer a numbering where both x and y correspond to straight lines

of hexes, i.e., letting x increase (with constant y) by going right

and y increase (with constant x) by going 60 degrees down from right

(assuming (0,0) is top left corner).

This way, if you move in one of the three "natural" directions, you

either have constant x, constant y or constant (x+y).

That makes calculation of distances etc. easier, as you don't have to

sepcial-case on odd and even rows.

I assume you know the hex coordinates and want to find the distance in

number of hexes while moving across edges.

If you had used the alternative numbering I described above, the

distance is calculated as follows:

mydistance((x1,y1), (x2,y2))

= if x1>x2 then mydistance((x2,y2), (x1,y1))

else if y2>=y1 then x2-x1 + y2-y1

else max(x2-x1, y1-y2)

With the numbering shown on the webpage you sited, you can calculate

distance as follows:

yourdistance((x1,y1),(x2,y2))

= mydistance((x1 - y1 `div` 2,y1), (x2 - y2 `div` 2,y2))

I.e., convert to the simpler coordinate system and calculate distance

in that. You convert by subtracting half the y coordinate (rounded

down) from the x coordinate.

Torben

**References**:**Calculating distance using hex coordinate system***From:*me

**Re: Calculating distance using hex coordinate system***From:*Torben Ægidius Mogensen

- Prev by Date:
**Re: Calculating distance using hex coordinate system** - Previous by thread:
**Re: Calculating distance using hex coordinate system** - Next by thread:
**Re: Calculating distance using hex coordinate system** - Index(es):