Hello all,I need to check the click on a 2D gameobject. I’ve tried this:
if (Input.GetMouseButtonDown(0))
{
Ray2D ray = new Ray2D(Camera.main.ScreenToWorldPoint(new Vector2(Input.mousePosition.x, Input.mousePosition.y)), Vector2.zero);
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
if (hit.collider!=null)
{
Debug.Log(hit.collider.gameObject.name);
}
}
but it doesn’t work…
So I tried to pass a 3d ray on a Physics2D.Raycast
if (Input.GetMouseButtonDown(0))
{
Ray b=Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(b.origin, b.direction);
if (hit.collider!=null)
{
Debug.Log(hit.collider.gameObject.name);
}
}
But it doesn’t work too,I’ve also tried to manually set a distance and a direction in the ray’s declaration and in the raycast’s physics2d.raycast method but it didn’t change nothing. This piece of code is in the Update method but I tried it also on the FixedUpdate but it was the same thing.
The only time when it detected some colliders is when i set the direction to -vector2.up but it detects only the terrain gameobjects.I tried to hack it by setting the origin to a higher point and reducing the distance but it didn’t work well,it doesn’t detect all the colliders. I searched on the internet almost all the arguments about detecting a click in a 2d context,I found the OnMouseDown() method but I prefer using the raycasting,to learn it. I’ve also seen that a lot of people use these 2 ways to detect a click but it doesn’t work to me. What’s wrong?
Thank you in advance for your help