How to get the position of a tile in a tilemap?

I am trying to figure out how to get the world space position of a specific tile from a tilemap.
This is what I tried so far:

Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.GetRayIntersection(ray, Mathf.Infinity);

if (Input.GetMouseButtonDown(0))
{
    if (hit.collider != null)
    {
        Debug.Log(hit.point);
    }
}

The problem with this is that is gets the point of contact and not the position of the tile in world space.

var pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var noZ = new Vector3(pos.x, pos.y);
Vector3Int mouseCell = grid.WorldToCell(noZ);

You can ask the grid component parent to your tilemap or the tilemap itself to translate from worldspace to cellspace.

2 Likes