Search code examples
c#unity-game-enginegame-developmentraycasting

Why is my GameObject traveling along the ray I am casting when I set transform.position = hit.point? Unity 3D


I am trying to get an object to follow my mouse along the surfaces in my game. There is a floor and other objects in the game. The object should always be on the floor or on one of the other objects. What I want is for the object's position to change to where the mouse is moved. I am doing this by casting a ray from the mouse. When the ray hits a collider the object's position should change to where it hit.

When I hit play the object moves along the ray that is being cast, starting at the collision (hit.point) and traveling towards the camera. Once it reaches the camera it starts over at hit.point and repeats. When I move the mouse the object's position changes to the new hit.point and moves toward the camera. The value of hit.point changes in the dev log when I move the mouse as it should and when the mouse stays still the value does not change, even though the object is still moving towards the camera. Why is this happening? It seems like because the value of transform.position is set to hit.point and never changed elsewhere in the code that the position should always be hit.point.

This is the code attached to the object that is moving:

public class FollowCursor : MonoBehaviour
{
    void Update()
    {
        RaycastHit hit;
        Ray ray;
        int layerMask = 1 << 8;
        layerMask = ~layerMask;
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
            transform.position = hit.point;
        Debug.Log(hit.point);
    }
}

This is a screenshot of my hierarchy and scene. The white sphere is the object that is moving. The floor I referred to is the sand at the bottom of the tank. I want the object to be on the sand or one of the other objects. Layer 8 is the tank itself, which is being excluded from the raycast because I do not want the object to be on the tank.


Solution

  • Because your GameObject has a collider too

    The ray hits the ground. The object goes there

    The next frame, the ray hits the object. The object moves there (the ray hit the surface, the pivot is in the center, so it moves towards the camera an amount equal to the radius of the collider, looks like 0.5 units based on your screenshot).

    Repeat.

    The best way to fix this is to put your ground on its own layer and raycast only against the layers you want the ray to hit using a LayerMask.