Detecting a click on a specific tile in a tilemap

Viewed 980

I'm trying to detect when the mouse clicks on a specific tile on a tile map. The game I'm making is a overhead 2d style, and I want to trigger code when a specific resource node (tile) is clicked on. I've tried to use RaycastHit2D:

public class DetectClickOnTile : MonoBehaviour
{
     Vector2 worldPoint;
     RaycastHit2D hit;

     // Update is called once per frame
     void Update()
     {

         worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);

         if (Input.GetMouseButtonDown(0))
         {
             hit = Physics2D.Raycast(worldPoint, Vector2.down);

             if (hit.collider != null)
             {
                Debug.Log("click on " + hit.collider.name);
                Debug.Log(hit.point);
             }      
     }
 }

But it only detects collision with the tilemap itself and not any of the individual tiles. Does anyone know why that is? For reference this is the map im trying to detect collision on, only the black tiles are filled in with placeholders, the rest of the tilemap is left blank for now. enter image description here

1 Answers

Afaik you can get the tile at the given world hit point using something like e.g.

// Reference this vis the Inspector
[SerializeField] TileMap tileMap;

...


    hit = Physics2D.Raycast(worldPoint, Vector2.down);

    if (hit.collider != null)
    {
        Debug.Log("click on " + hit.collider.name);
        Debug.Log(hit.point);

        var tpos = tileMap.WorldToCell(hit.point);

        // Try to get a tile from cell position
        var tile = tileMap.GetTile(tpos);

        ...
    }      

However, I'm pretty sure your Raycast is not what you want to use but rather directly try and get the tile from the worldPoint and if you got one you hit one ;)

Your Raycast goes down meaning you cast from the click point to the bottom of the screen which doesn't sound like what you are trying to achieve.

So probably rather something like

 if (Input.GetMouseButtonDown(0))
 {
     worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
         
     var tpos = tileMap.WorldToCell(worldPoint);

     // Try to get a tile from cell position
     var tile = tileMap.GetTile(tpos);

     if(tile)
     {
         ...
     }
}
Related