Home unity3d Neighboring cells in hexagonal telmape

# Neighboring cells in hexagonal telmape

Author

Date

Category

Is there a way to get neighboring cells for tilemap? For hexagonal grid, rectangular coordinates are used, but I do not understand how they are distributed, so it does not turn out the standard offset. You can return excessive (i.e. 8, as for a square), but this option does not fit me.

Chuuter know that the answer is elementary, but I can’t prove 🙂

figured out independently.

tl; dr

So (if you need lazy calculations):

``````ionumerable & lt; vector3int & gt; GetneighBours (Vector3Int Cell) {
Var Yeven = Cell.y% 2 == 0;
Yield Return Cell + New Vector3int (+1, +0, 0); // Horizontal right
Yield Return Cell + New Vector3int (-1, +0, 0); // Horizontal left
Yield Return Cell + New Vector3int (+0, +1, 0); // Diagonal Upper (for an even row - right, for odd - left)
Yield Return Cell + New Vector3int (+0, -1, 0); // Diagonal Nizhny (for a series of rows - right, for odd - left)
Yield Return Cell + Yeven
. new vector3int (-1, +1, 0) // Thorn row, diagonal top left
: new vector3int (+1, +1, 0); // odd row, diagonal top right
Yield Return Cell + Yeven
. new vector3int (-1, -1, 0) // Thorn row, diagonal bottom left
: new vector3int (+1, -1, 0); // The odd row, the diagonal bottom right
}
``````

or, for example, so (if you need, for example, an array):

``````vector3int [] getneighbours (vector3int cell) = & gt; new [] {
Cell + New Vector3INT (+1, +0, 0),
Cell + New Vector3int (+0, +1, 0),
Cell + New Vector3int (-1, +0, 0),
Cell + New Vector3int (+0, -1, 0),
Cell + Cell.y% 2 == 0? new vector3int (-1, +1, 0): new vector3int (+1, +1, 0),
Cell + Cell.y% 2 == 0? new vector3int (-1, -1, 0): new vector3int (+1, -1, 0)
};
``````

What is happening here?

It’s not in Unity and not in Tilemap, it is in principle to use rectangular coordinates for a hexagonal grid. In the usual cell mesh are located as follows:

in hexagonal (which is also rectangular, but well masked) so:

i.e., odd rows are shifted there to the right so that each cell has no more than six neighbors. Neighbors along the X axis (horizontal) will always be calculated equally, because They are in the same row. Neighbors on y (diagonal) for different rows are calculated in different ways. Since the ranks are shifted to each other in different directions.

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.