- Home /
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);
}
}
}
Don't forget to accept the answer, not just vote it. Thanks ;)
I'm not sure if either of the answers is really the thing to fix your problem. You should probably rather look into getting the absolute mouse position on screen and transfor$$anonymous$$g that to a position that you want your object to be. Also don't forget to take your camera perspective into account and how that affects a object position in relation to the mouse if its not exactly in screenspace.
he said that his code was working but wasnt moving smoothly, and the easiest solution is rather than teleporting to the position the user clicked (like he is doing and and you suggested) is to movetowards the position, using the vector3.movetowards, in a linear velocity way.
Answer by bpaynom · Jan 30, 2019 at 08:09 AM
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.
Answer by xxmariofer · Jan 30, 2019 at 08:18 AM
Like @ConcanoPayno pointed, dont catch inputs in the fixedupdate. but what y9u are looking for is something like https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html rather thans translating the oobject to one specific point.
Your answer
Follow this Question
Related Questions
How to find a transform with name in prefab 2 Answers
Calculating where to position instantiated clone 1 Answer
How to make the camera acquire the position of a gameobject and start following it? 1 Answer
collider position wrong object position in collider 0 Answers
Change position of an object on a keystroke within a trigger only? 1 Answer