- Home /
Camera.main.ScreenToWorldPoint not outputting expected results.
Hey, this one has been stumping me for a few days now, and I keep avoiding it.
So, I'm trying to do a simple Raycast from mouse position to the world. I'm using: Physics.Raycast( Camera.main.ScreenToWorldPoint(Input.mousePosition), Camera.main.transform.TransformDirection(Vector3.forward), mouseHitInfo ); //Cast down
Which didn't seem to be giving me the results I was expecting, so I logged the output, and Camera.main.ScreenToWorldPoint is giving me the same position every single time. (10, 12, 3).
As a note I'm using a camera facing down, on a 30 degree angle. I am calculating that angle in the code above with TransformDirection, so I don't see the issue...
Any help on the matter is much appreciated, and thanks in advance.
-Rob
Wow, you're a life saver. No clue to use ScreenPointToRay, thanks :)
Ins$$anonymous$$d of transform.TransformDirection(Vector3.forward)
, you can just do transform.forward
.
Answer by Waz · Jun 24, 2011 at 12:32 AM
The reason your code doesn't work is that Input.mousePosition has a zero Z co-ordinate - i.e. 0 units from the camera, which I'm guessing was at (10,12,3). ScreenPointToRay ignores the Z and produces a Ray from the camera through the screenpoint, which you can then use as a raycast. To understand this, note that the Ray you get from ScreenPointToRay always has its origin at the Camera (it will be (10,12,3) in your case, since that is the line from your eye (the camera) through the mouse position, into the world.
Your answer
Follow this Question
Related Questions
mouse position on terrain 1 Answer
Camera.ScreenToWorldPoint with Perspective camera 1 Answer
Raycast hitting objects to the left of my player 1 Answer
Ray Cast not working for camera. 1 Answer