Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

2D How to Detect if sprite is touched ?

Discussion in '2D' started by Merhat, May 10, 2015.

  1. Merhat

    Merhat

    Joined:
    May 9, 2015
    Posts:
    10
    2D How to Detect if sprite is touched ?
    i try to make the game for android but first i need to make the buttons they are sprites and how to detect if they are touched ? :)
    i write on C#
     
  2. Nitugard

    Nitugard

    Joined:
    May 10, 2015
    Posts:
    343
    Hello Merhat,

    To detect when the user touch the sprite you would need to:
    • Get touch position
    • Convert that touch position from screen to world point
    • Then use Physics2D.OverlapPoint to check if your touching any collider( so you need to have 2d collider attached to the sprite gameobject)

    Final code:
    Code (CSharp):
    1. Vector3 worldPoint = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
    2. Vector2 touchPos = new Vector2(worldPoint.x, worldPoint.y);
    3. if (col == Physics2D.OverlapPoint(touchPos)){
    4.  
    5. }
     
    theANMATOR2b and Alef_Ribeiro like this.