Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detect tap on a 2d animation on unity3d

I have a 2d animation on scene.When I try to detect tap or click on the animation using OnMouseDown function it doesn't work.But it works using the following code

Input.GetMouseButtonDown(0)

it works but it detects tap on whole window and if I print the onject name like

Debug.log(this.name);

it prints the name of the animated sprite name.I want to detect tap only on the animated sprite.Please anyone help me..

like image 662
BlackJack Avatar asked Dec 01 '25 10:12

BlackJack


1 Answers

You need to use Raycasting to detect that. Cast a 2D ray down from the input location and check if it hits something. Here's good info about it.

if (Input.GetMouseButtonDown(0))
{
    var hit : RaycastHit2D = Physics2D.Raycast(cam.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

    if(hit != null)
    {
        Debug.Log("object clicked: "+hit.collider.tag);
    }
}
like image 81
Esa Avatar answered Dec 04 '25 00:12

Esa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!