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?
No, not really. It seems like it's normal that Input.mousePosition returns positions on the screen. This seems to be a raycast bug of some sort. In our project the same code that works for raycasts in one script/class/component doesn't work in another one.
Even going back to an earlier save of the project (where the raycast used to work in said class where it stopped working) doesn't fix it. So I think it's a bug in the recent Unity version. Anyone knows how to report that?
Answer by tormentoarmagedoom · Jul 30, 2018 at 07:41 AM
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 :D
Yeah I've kinda realized that by now... it doesn't solve the issue though that the raycast function, which is the standard thing they suggest in the tutorials just doesn't return any game objects below the mouse.
So I used Debug.DrawRay to find out where the hell the raycasts are going. Which happened to be the Canvas.