Raycast shooting in direction of Canvas instead of game object below mouse

Hello everyone,

I’ve got the problem that I’ve got a UI canvas in my scene, but also want to target game objects with a raycast. For some reason the raycast goes in direction of the Canvas instead of the game game object below the mouse.

That’s basically my code:

if(Input.GetMouseButtonDown(0))
{
                RaycastHit raycastHit;
                Debug.DrawRay(Camera.main.transform.position,   Input.mousePosition, Color.red);
                Debug.Log(Input.mousePosition);
                if  (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out raycastHit))
                {
                       //do stuff;
                 }
}

It clearly shoots rays at the Canvas instead of the objects in game space. I’m using a “Screen Space - Overlay” canvas. Is there some way to make it shoot rays at the game space instead of the canvas that’s sitting elsewhere?

Good day.

You are little lost… You need to read the API pages before coming ask for help…

Input.mousePosition returns the SCREEN position of the mouse, thats what the function does. What you need is to convert the screen position into worldposition.

If you llok for 3 minutes in Unity Answers/google you will find your solution…

Go read Camera.ScreenToWorldPoint and will find your solution!

Bye :smiley: