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);
}
}
}