Hexagon-Grid Distance

How is it possible to calculate distance between two tiles? I want to get the number of tiles of the distance;

Here is my grid:

i tried a lot of solution till this the best was this

var distanceVector : Vector2 = Vector2(Mathf.Abs(a.pos.x-b.pos.x),Mathf.Abs(a.pos.y-b.pos.y));
distance = Mathf.Ceil(Mathf.Sqrt((distanceVector.x*distanceVector.x)+(distanceVector.y*distanceVector.y)+(distanceVector.x*distanceVector.y)));

Read through Hexagonal Grids. It describes most hex grid representation and has a section in how to get distances for each of them, not to mention the other things you will find useful for hex grid games.

maccabbe posted an excelent link on that subject. However they seem to suggest to use a 3 coordinate system instead of 2. As you can read in the post it has some advantages. However if you want to stick with yours that’s not a problem.

Just you look at your structure. You have layed out straight rows. That means if you only move on x axis the number of tiles equals the distance in that direction. Now if you move only along the y axis you also always need as many tiles as it is away in y. The point is if you move 2 times in y you can see that you either end up at the same x position or one x position shifted (left or right). That means for every 2 y moves you can save 1 x move

int GetTileDistance(int aX1, int aY1, int aX2, int aY2)
{
    int dx = aX2 - aX1;     // signed deltas
    int dy = aY2 - aY1;
    int x = Mathf.Abs(dx);  // absolute deltas
    int y = Mathf.Abs(dy);
    // special case if we start on an odd row or if we move into negative x direction
    if ((dx < 0)^((aY1&1)==1))
        x = Mathf.Max(0, x - (y + 1) / 2);
    else
        x = Mathf.Max(0, x - (y) / 2);
    return x + y;
}

Note: the aDelta/2 is an integer division. So it’s rounded down. The Max function is needed since we can only save x moves. If we only move along the y axis there’s nothing we can save.

edit
Forgot the “Abs” on each delta value ^^

another edit
Just realized that the “saving” in x moves is a bit different when you move to the left instead of right. I fixed the method and rearranged the code so it’s more readable.

the final x and y values are actually the required moves in each direction. Keep in mind that the y moves can contain those “saved” x moves as you can switch direction every step. The method of course calculates the shortest path ^^

*** third edit ^^ ***

I just discovered that the distance also depends on if you start on an odd or even row ^^. I first thought that this is going to bee too complex, but finaly i thing i got a solution that works everytime. Now you don’t have to pass the relative vector but the two points in the grid (as you need to know if we start on an odd or even row).

Just in case you’re wondering (aY1&1)==1 does the odd even test. Also keep in mind that “^” is the xor operator. So either one or the other should be true but not both.