1
\$\begingroup\$

So i ran into this problem today. I want to have a perspective camera and sprites that are rotated by lets say 1.5 on the X axis. The problem is that the 2D raycast does not work correctly, it returns the wrong colliders. Here is the implementation:

Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            RaycastHit2D hit = Physics2D.Raycast(mousePos, Vector2.up);
            if(hit.collider)
            {
                Debug.Log(hit.collider.gameObject.name);
            }

Now if my camera is orthographic everything works great. How can I make it work with a perspective camera? Should I use 3d colliders and raycasts ?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Have you considered using the EventSystem instead of raycasting yourself?

In a nutshell:

  1. Add a "Physics2DRaycaster" componenent to your camera

  2. Add a 2D collider to your GameObject

  3. Create a class that implements UnityEngine.EventSystems.IPointerClickHandler, and place it on your object with the collider.

You will find that the EventSystem can be enormously useful, it has a decent array of interfaces beyond the one listed above.

Check out this great little video for more if you are interested, it contains some examples of how to use the EventSystem for various things like making sure your clicking on an object and not part of the UI, how to replace OnMouseDown, etc.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .