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 GreenPixel-ltd, Mar 16, 2019.

  1. GreenPixel-ltd

    GreenPixel-ltd

    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. GreenPixel-ltd

    GreenPixel-ltd

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

    RidgeWare

    Joined:
    Apr 12, 2018
    Posts:
    67
    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 .
     
    GreenPixel-ltd likes this.
  4. SirStompsalot

    SirStompsalot

    Joined:
    Sep 28, 2013
    Posts:
    112
    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.  
     
    GreenPixel-ltd likes this.
  5. GreenPixel-ltd

    GreenPixel-ltd

    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:
    112
    Heh, right on, I abandoned Isometric 2.5D Toolset in favor of Unity's tilemaps. Glad you found a solution that works.