Tilemap select tile with mouse issue

Hello,

I have a top-down 2d TileMap without colliders and I am trying to detect a tile via mouse input. I have the basics working, however the tile selection appears to sometimes have an offset (i.e. inaccurate.)

So far, I have tested ScreenPointToRay and ScreenToWorldPoint:

// MouseEvent.cs in update()
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 worldPoint = ray.GetPoint(-ray.origin.z / ray.direction.z);
//Vector3 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
onMouseClickEvent(worldPoint);

Then in my TileMap via observer pattern (delegate/event):

private void onMouseClickEvent(Vector3 point) {
    Vector3Int cellIndex = map.WorldToCell(point);
    Debug.Log("Position: " + point + " [" + cellIndex + "]");
    highlightTile(new Vector2(cellIndex.x, cellIndex.y));
}

private void highlightTile(Vector2 dest) {
     // highlightBox = opaque green tile prefab.
    GameObject tile = Instantiate(highlightBox, dest, Quaternion.identity);
    highlightTiles.Add(tile); // List<GameObject> so I can Destroy() later
}

Mouse click example with highlighted tile:


Camera is Orthographic, size=5, scale 1,1,0.
TileMap scale is 1,1,0.

I’d really appreciate any help.

Thank you.

You’re creating the HighlightBox at the mathematically correct cell, but the Vector3 returned by map.WorldToCell(point) represents the bottom-left coordinate of the cell (the point at which the grid lines cross), so your HighlightBox appears to be offset from the contents of the cell. What you want is to instantiate it at the center of the cell, which you can get from the TileMap method GetCellCenterLocal.

For example:

private void onMouseClickEvent(Vector3 point)
{
    Vector3Int cellIndex = map.WorldToCell(point);
    Debug.Log("Position: " + point + " [" + cellIndex + "]");
    highlightTile(cellIndex);
}
private void highlightTile(Vector3Int dest)
{
    // highlightBox = opaque green tile prefab.
    GameObject tile = Instantiate(highlightBox, map.GetCellCenterLocal(dest), Quaternion.identity);
    highlightTiles.Add(tile); // List<GameObject> so I can Destroy() later
}