- Home /
Raycast - screen position to world position not precise
Hi, I'm trying to select a game object by clicking on it with the mouse. This generally works, except that I find it's not very precise in some cases.
I'm using "Camera.main.ScreenPointToRay(Input.mousePosition)" to convert the mouse position into a world position and then raycasting from the camera towards my game objects.
As you can see from the first screenshot, it looks like the mouse is hovering over a spaceship. However, the raycast is not detecting the collision. When I look in the editor, the raycast (green line) is just missing the ship's collider.
Could this be related to having the camera far from the ship (roughly 1000 units)? Could it be related to the object and camera not being near the origin (0,0,0)?
Any help with this is appreciated!
This is the code I'm using:
// Create a ray with the origin at the camera's position. The direction of the
// ray is deter$$anonymous$$ed by the mouse position.
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// Do a raycast towards the world location the mouse is pointing at
RaycastHit HitInfo;
float $$anonymous$$axDistance = 1400f;
bool HitSomething = Physics.Raycast(ray, out HitInfo, $$anonymous$$axDistance, TheLayer$$anonymous$$ask);
// Draw a debug line
Debug.DrawLine(ray.origin, ray.origin + ray.direction * $$anonymous$$axDistance, Color.green);
Your answer
Follow this Question
Related Questions
Is there a way to get mouse position in 3D space at a given y-value? 2 Answers
2D - finding object at mouse position 2 Answers
Weird navigation issue 0 Answers
What is error on Raycasting? 0 Answers