- Home /
SOLVED - Raycast to detect GameObject having the shortest hit distance
Dear Unity Community,
I am struggling with a problem in my Unity project and read many threads on raycasting but can not figure out the solution.
There are many objects on the scene having the same script on it (dragging, rotating, scaling objects based on mouse movements).
When ray aligned to Input.mousePosition hits more than 1 game object dragging works on all objects being hit.
What I would like to happen instead is to detect which has the shortest hit distance, and move only that game object. I would really appreciate any ideas how to solve it. Thanks in advance.
//LEFT MOUSE CLICK DRAG AND DROP
if(Input.GetMouseButton(0))
{
ray=Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray,hit))
{
hit.collider.transform.position.x=hit.point.x;
hit.collider.transform.position.y=hit.point.y;
}
}
Answer by robertbu · Sep 28, 2013 at 09:19 PM
Assuming the above script is on many objects, your problem is not that the raycast is hitting multiple objects, but that it moves objects even if they are not the ones hit. A Physics.Raycast() returns the first (nearest) object hit. Assuming this code is on a bunch of objects, you can fix the logic by:
if(Physics.Raycast(ray,hit) && hit.transform == transform)