JonHerbert
JonHerbert

Reputation: 677

Getting neighbours from the Tilemap in Unity

I am using the hexagonal tilemap and am trying to store data on each tile; localPos, worldPos, name, etc. and one of the things I'm trying to access are the immediate neighbours from each side. I have begun by using the scripts here to get started:

https://medium.com/@allencoded/unity-tilemaps-and-storing-individual-tile-data-8b95d87e9f32

But I cannot find any information about storing neighbours. I am assuming it may have something to do with BoundsInt or cellBounds but am not sure and the docs are currently limited.

One thing I have tried to do is create gameobjects using the world position and this places them where they are supposed to be, but I think I may be overcomplicating it.

Has anyone else had any luck with this?

Upvotes: 3

Views: 3552

Answers (2)

Erel Segal-Halevi
Erel Segal-Halevi

Reputation: 36813

I found this question while looking for a formula to get the 6 neighbors of a given tile. For this grid:

enter image description here

It turns out that the formula depends on whether the y coordinate of the current node is even or odd. Here is the code that worked for me;

static Vector3Int
    LEFT = new Vector3Int(-1, 0, 0),
    RIGHT = new Vector3Int(1, 0, 0),
    DOWN = new Vector3Int(0, -1, 0),
    DOWNLEFT = new Vector3Int(-1, -1, 0),
    DOWNRIGHT = new Vector3Int(1, -1, 0),
    UP = new Vector3Int(0, 1, 0),
    UPLEFT = new Vector3Int(-1, 1, 0),
    UPRIGHT = new Vector3Int(1, 1, 0);

static Vector3Int[] directions_when_y_is_even = 
      { LEFT, RIGHT, DOWN, DOWNLEFT, UP, UPLEFT };
static Vector3Int[] directions_when_y_is_odd = 
      { LEFT, RIGHT, DOWN, DOWNRIGHT, UP, UPRIGHT };

public IEnumerable<Vector3Int> Neighbors(Vector3Int node) {
    Vector3Int[] directions = (node.y % 2) == 0? 
         directions_when_y_is_even: 
         directions_when_y_is_odd;
    foreach (var direction in directions) {
        Vector3Int neighborPos = node + direction;
        yield return neighborPos;
    }
}

Upvotes: 4

Chance Shaffer
Chance Shaffer

Reputation: 124

      If the article above is being followed, perhaps make another function that is invoked by each object will do it. Have the function store either the GameObjects or the positions themselves inside the current "anchor" tile inside some data structure of your choice. While this may be more cumbersome, it will allow more flexibility.

TL;DR
      To GameTile add another data structure for stored neighbors. Then either create a private function to instantiate the neighbors or just outright create them at the tracked x and y position. Then store the instantiated neighbors into the data structure.

Upvotes: 0

Related Questions