Search Unity

Tilemap: if I my sprite bigger than one tile how can I catch a click event on it

Discussion in '2D' started by Denis-Shevchenko, Mar 16, 2019.

  1. Denis-Shevchenko

    Denis-Shevchenko

    Joined:
    Jul 17, 2016
    Posts:
    17
    Hi,
    So I have pretty simple question:
    "if I my sprite bigger than one tile how can I catch a click event on it"

    I already spend a day looking for the answer

    Any thoughts how can I do that?
    I will be appreciate for any help.
     
  2. Denis-Shevchenko

    Denis-Shevchenko

    Joined:
    Jul 17, 2016
    Posts:
    17
  3. RidgeWare

    RidgeWare

    Joined:
    Apr 12, 2018
    Posts:
    65
    Have you looked into polygon colliders that match the sprite outline? You just drag the sprite onto the collider component and it should fill it out properly. Then it will detect clicks in all the pixels in the sprite.

    I haven't played around with it myself but there's lots of search results out there from others who have .
     
    Denis-Shevchenko likes this.
  4. SirStompsalot

    SirStompsalot

    Joined:
    Sep 28, 2013
    Posts:
    99
    There are two ways to do this:

    Break up each object into individual tiles. Your tile looks to be 5x5ish, so you'd be creating 25 different sprites. From there, you can collide with them normally using the composite collider for the tilemap. But this is a rubbish idea.

    Alternatively (The way I selected) is to create the tiles as prefabs. I selected PolygonCollider2D for my objects. You would add the prefab to the tilemap, then apply click logic as normal.

    Code (CSharp):
    1.  
    2. public Vector3 MousePositionWorld()
    3. {
    4.     Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    5.     return ray.GetPoint(-ray.origin.z / ray.direction.z);
    6. }
    7.  
    8. // ...
    9.  
    10. if (Input.GetMouseButtonDown(0))
    11. {
    12.     RaycastHit2D[] hit = Physics2D.RaycastAll(MousePositionWorld(), -Vector2.up, 1f);
    13.     for(int i = 0; i < hit.Length; i++)
    14.     {
    15.         if (hit[i].collider != null)
    16.         {
    17.             Debug.Log(hit[i]);
    18.         }
    19.     }
    20. }
    21.  
     
    Denis-Shevchenko likes this.
  5. Denis-Shevchenko

    Denis-Shevchenko

    Joined:
    Jul 17, 2016
    Posts:
    17
    Thank you, but I already decided to use isometric 2.5d toolset, because of simplicity of adding new sprites (you do not need to suffer with pivot point) and because you could use sprites with multiple-tiles size and it will not break sorting and many many others reasons..
     
    SirStompsalot likes this.
  6. SirStompsalot

    SirStompsalot

    Joined:
    Sep 28, 2013
    Posts:
    99
    Heh, right on, I abandoned Isometric 2.5D Toolset in favor of Unity's tilemaps. Glad you found a solution that works.