How do I move my object smoothly using mouse,How do I make the object movement smooth ?

I want my object to move only when it is clicked on by the mouse and the mouse remains clicked. Once clicked, the object should move with the mouse wherever it goes.

I use the following code but the movement is not smooth and sometimes the object moves away from the mouse’s location, usually lagging behind. Ive put this code in the FixedUpdate() function.

    if (Input.GetMouseButton(0))
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit, Mathf.Infinity))
        {
            if (hit.transform.name == "pocketofcoin")
            {
                float moveLR = Input.GetAxis("Mouse X") * mouseSensitivityX;
                float moveUD = Input.GetAxis("Mouse Y") * mouseSensitivityY;

                float _x = transform.position.x + moveLR;
                float _y = transform.position.y + moveUD;

                transform.position = new Vector2(_x, _y);
            }
        }
    }

It’s a bad idea to put Input in FixedUpdate() because it’s not called every frame, so you lose some input.


Second, there are these functions that may help you OnMouseDown , OnMouseDrag , OnMouseUp.

Like @ConcanoPayno pointed, dont catch inputs in the fixedupdate. but what y9u are looking for is something like Unity - Scripting API: Vector3.MoveTowards rather thans translating the oobject to one specific point.