- Home /
Physics.Raycast (ray, hit) strange behaviour
I'm making a jewels like game. I select 3D jewels with a mouse click. I do it using
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast (ray, hit)){ bla-bla-bla
Everything was fine until i moved the camera from z:-630 to z:-730. Now the ray hits jewels that are lower than the mouse position (if on the top of the screen, and vice versa if on the bottom). But works fine if selecting a jewel in the middle of the screen.
Is it a kind of a delta growing with camera distance?
The camera field of view is 1 (i don't want orthographic though it has the same problem).
Answer by Nordir · Jan 03, 2013 at 07:32 PM
While trying to draw a debug ray i discovered that my 2nd camera for background had a "MainCamera" tag (cause i had simply cloned it ofcourse). If two cameras were close everything went OK, if not - they calculated the stuff differently. Ha-ha :)
Sorry folks for disturbing you!
Answer by Jeffom · Jan 03, 2013 at 05:45 PM
Set the screen resolution of your game screen to a fixed one
Answer by MibZ · Jan 03, 2013 at 04:12 PM
When dealing with Y values in screen coordinates you have to subtract the Y position from Screen.height.
Try this: var ray: Ray = Camera.main.ScreenPointToRay(new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y));
So if i click in the left bottom corner (0, 0) i will get Screen.height in "Screen.height - Input.mousePosition.y". Why would i want this? :)
I don't know exactly why it works as it does, something to do with the math Unity does that we don't see, but whenever my Y coordinates are inverted this corrects the problem, whether it is dealing with converting a touchscreen tap into a 3D coordinate or placing a GUI element over a GameObject.
Try it.
You really don't need to, and shouldn't, subtract the Y from Screen.height. The only time you would ever do that is converting Input.mousePosition to GUI coordinates for use in OnGUI, but even then, you'd simply use Event.current.mousePosition rather than Input.mousePosition, so it's still not necessary. Besides, the question is asking about raycasting, which excludes OnGUI entirely.
Eric5h5, i know u are the Unity megamonster (in a good way) :) U must have an answer to my question! :)
I know that the question didn't ask about OnGUI, I mentioned that as a side note. His question describes that when converting screen coordinates (mouse position) to world coordinates, the Y values are inverted, and when I ran into that problem the solution I found (here on Unity Answers) said to subtract the Y value from Screen.height, and every time I have done that it has worked.
If that isn't it, what is?
Your answer
Follow this Question
Related Questions
I don't know why i can't detect by ray sth. tagged, 1 Answer
Exclude tag from raycast 1 Answer
how to get info on what raycast hitted 1 Answer
Raycast on mini-map 0 Answers