Home > front end >  How to get surrounding tiles in Unity?
How to get surrounding tiles in Unity?

Time:09-29

I am working on a peace of code, in which I need to find all surrounding tiles of a tile. I can get the target tile, but cannot find the way to get it's neighbors.

Here is the code I have:

public List<TileBase> FindAllTileNeighbors(Vector2 gameOjectPosition){
    List<TileBase> sTiles;
    GridLayout grid = map.GetComponentInParent<GridLayout>();
    Vector3Int gridPosition = grid.WorldToCell(gameOjectPosition);
    TileBase tile = map.GetTile(gridPosition);

    // TODO: find surrounding tiles

    return sTiles;
} 

CodePudding user response:

"All neighbours" is a bit unspecific.

From you only passing in a 2D position I'd assume you only want to find neighbours within the XY plane.

You already have the gridPosition so you could simply do

// This allows you to use queries on IEnumerable types
// see example at the bottom
using System.Linq;

...

private readonly Vector3Int[] neighbourPositions = 
{
    Vector3Int.up,
    Vector3Int.right,
    Vector3Int.down,
    Vector3Int.left,
    
    // if you also wanted to get diagonal neighbours
    //Vector3Int.up   Vector3Int.right,
    //Vector3Int.up   Vector3Int.left,
    //Vector3Int.down   Vector3Int.right,
    //Vector3Int.down   Vector3Int.left
};

public List<TileBase> FindAllTileNeighbors(Vector2 gameOjectPosition)
{  
    var grid = map.GetComponentInParent<GridLayout>();
    var gridPosition = grid.WorldToCell(gameOjectPosition);
    
    if(!map.HasTile(gridPosition))
    {
        Debug.LogWarning($"The position {gridPosition} does not exist in the map!");
        return new List<TileBase>();
    }

    var sTiles = new List<TileBase>();
    foreach(var neighbourPosition in neighbourPositions)
    {
        var position = gridPosition   neighbourPosition;

        if(map.HasTile(position))
        {
            var neighbour = map.GetTile(position);
            sTiles.Add(neighbour);
        }
    }
    return sTiles;

    // or using Linq you could also write it as
    //return (from neighbourPosition in neighbourPositions select gridPosition   neighbourPosition into position where map.HasTile(position) select map.GetTile(position)).ToList();
} 
  • Related