raycast mouse detects any object
Hi, i want to detect a mouse click on a especific object using raycast, but for some reason my code detects all the objects that have a collision when you click on them, here is my code.
if(Input.GetMouseButtonDown(0))
{
Vector2 MousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D Hit = Physics2D.Raycast(MousePos,Vector2.zero);
if(Hit)
{
gameObject.GetComponent<Animator>().SetBool("Push", true);
MouseDown = true;
}
}
Thank you.
Answer by Sotocodes · Jan 13, 2021 at 11:23 PM
Hi @Fivii
You just need to find a way to ask what object was hit. There plenty of ways to do this, for example by checking if the object hit has a certain tag, or by playing around with physics layers, or even by just checking the name of the object that was hit. Taking that last solution and applying it to your code should be simple enough:
if (Input.GetMouseButtonDown(0))
{
Vector2 MousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D Hit = Physics2D.Raycast(MousePos, Vector2.zero);
if (Hit && Hit.collider.name == "NameOfYourGameobject")
{
gameObject.GetComponent<Animator>().SetBool("Push", true);
MouseDown = true;
}
}
Your answer
Follow this Question
Related Questions
Sound in Unity is not working! WHY? 0 Answers
See if objects overlap when user taps the screen 0 Answers
Diagonal Wall Jump help 0 Answers
Raycast problem/wall climb system 0 Answers
How to make this shop animation and unlock system? 0 Answers