How to get the cell position in Tilemap by GridNode vice versa

Get gridNode by cellPosition of tilemap

float HeightOfTile = 2.56f;
Vector3Int indexOfCell = new Vector3Int(i, j);
Vector3 worldPosition = tilemap.GetCellCenterWorld(indexOfCell);
worldPosition.y += HeightOfTile / 2f; // GetCellCenterWorld always return the bottom-center of the tile so I have to add half of the height of tile before changing it to the GridNode in case the boundary problem
GraphNode gridNode = AstarPath.active.data.gridGraph.GetNearest(worldPosition).node;

Get the cellPosition of tilemap by gridNode

float HeightOfTile = 2.56f;
var worldPosition = (Vector3)gridNode.position;
worldPosition.y -= HeightOfTile / 2f; // have to add this line or the cellPosition is the wrong one
var cellPosition = tilemap.WorldToCell(worldPosition);

for now, my project seems working fine but not sure if the solution is correct when add/substract 1.28f to the worldPosition.y;
I have aligned the hexagonal grid to my tilemap., wonder if somewhere exists API for me to do transformation between cellPosition in tilemap and gridNode in Astar

Hi

There’s no such conversion built-in at the moment. Though I think your conversion will be more stable if you base it on the grid coordinates, which can be accessed using gridNode.XCoordinateInGrid and gridNode.ZCoordinateInGrid.

Yeah, that’s exactly what I want, I’m going to find the formula between cellPosition and gridNodePosition
but I’m not very familiar with the X(Z)CoordinateInGrid, can you give me some hits about it,
Given :

  1. Tilemap size is 25 * 20,
  2. A* size is 40 * 30,
  3. (0,0) in cellPosition == (X, Y) in gridNodePosition

The formula I need:

  1. (a, b) in cellPosition => (?, ?) in gridNodePosition
  2. (a, b) in gridNodePosition => (?, ?) in cellPosition

I output some of the mapping between the two

finally I got the formula:
Given (0, 0) of cellPosition in tilemap == (_baseX, _baseY) of gridNodePosition in A* map
then

public static GridNode GetGridNodeByTileMapIndex(Vector3Int position)
        {
            int nx = position.x + _baseX + (position.y + 1) / 2;
            int ny = position.y + _baseY;
            return GridGraph.GetNode(nx, ny) as GridNode;
        }

public static Vector3Int GetTileMapIndexByGridNode(GridNode gridNode)
        {
            int y = gridNode.ZCoordinateInGrid - _baseY;
            int x = gridNode.XCoordinateInGrid - _baseX - (y + 1) / 2;
            return new Vector3Int(x, y);
        }
1 Like