0
\$\begingroup\$

How do I get all adjacent tiles to a hexagonal tile, my tile map is using a staggered co ordinate system with an odd stagger index and I am using libgdx java.

if (x % 2 == 0) {
            hexAdj[0] = new Vector2(x    , y + 1);
            hexAdj[1] = new Vector2(x + 1, y + 1);
            hexAdj[2] = new Vector2(x + 1, y    );
            hexAdj[3] = new Vector2(x    , y - 1);
            hexAdj[4] = new Vector2(x - 1, y    );
            hexAdj[5] = new Vector2(x - 1, y + 1);          
        }else{
            hexAdj[0] = new Vector2(x    , y + 1);
            hexAdj[1] = new Vector2(x + 1, y    );
            hexAdj[2] = new Vector2(x + 1, y - 1);
            hexAdj[3] = new Vector2(x    , y - 1);
            hexAdj[4] = new Vector2(x - 1, y - 1);
            hexAdj[5] = new Vector2(x - 1, y    );
        }
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I think the simplest way would be to convert your coordinates to cube coordinates, then use a lookup table with the offsets to get the coordinates for the adjacent tiles, and then convert the coordinates back.


Vector3 coordsToCube(Vector2 coords) {
    Vector3 cube = new Vector3();
    cube.x = coords.x - (coords.y - ((int) coords.y & 1)) / 2
    cube.z = coords.y;
    cube.y = -cube.x - cube.z;
    return cube;
}

Vector2 cubeToCoords(Vector3 cube) {
    Vector2 coords = new Vector2();
    coords.x = cube.x + (cube.z - ((int) cube.z & 1)) / 2;
    coords.y = z;
    return coords;
}

static Vector3[] offsets = new Vector3[] {
   new Vector3(+1, -1,  0), new Vector3(+1,  0, -1), new Vector3( 0, +1, -1),
   new Vector3(-1, +1,  0), new Vector3(-1,  0, +1), new Vector3( 0, -1, +1)
}

Vector3[] getAdjacent(Vector3 cube) {
    Vector3[] adjacent = new Vector3[6];
    adjacent[0] = new Vector3(cube).add(offsets[0];
    adjacent[1] = new Vector3(cube).add(offsets[1];
    adjacent[2] = new Vector3(cube).add(offsets[2];
    adjacent[3] = new Vector3(cube).add(offsets[3];
    adjacent[4] = new Vector3(cube).add(offsets[4];
    adjacent[5] = new Vector3(cube).add(offsets[5];
    return adjacent;
}

\$\endgroup\$
3
  • \$\begingroup\$ Ive added my code to my question it draws from a different ruleset depending if hex is on a odd or even row it works right now hexAdj[0] is the top adjacent tile all the way to 5 going clockwise around hexagon. Is this a good way to do it? \$\endgroup\$ Nov 23, 2015 at 14:40
  • \$\begingroup\$ There is nothing wrong with the way you are doing it, I just like to use cube coordinates because some algorithms are easier to implement using cubes. \$\endgroup\$ Nov 23, 2015 at 18:18
  • \$\begingroup\$ Here is a site explaining everything you need to know about hexagonal maps: redblobgames.com/grids/hexagons \$\endgroup\$ Nov 23, 2015 at 18:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .