I wanted to make object that will follow the mouse cursor with it`s own speed, but when this object reaches the mouse it begins to twitch. Any way i can make it not twitch?
To fix the problem, first calculate the distance to the mouse.
If the object is close enough to the mouse then stop the object by setting the velocity to zero.
If the object is far away enough then calculate the velocity vector according to the mouse position.
Example: (I haven’t tested the code because I do not have Unity on this computer)
public float DistanceThreshold = 0.05f; // TODO: Adjust this value
void FixedUpdate()
{
Vector2 mousePositionInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition)); // Keeps only X and Y because we're declaring a Vector2
Vector2 objectPositionXY = transform.position; // Keeps only X and Y because we're declaring a Vector2
Vector2 vector2TowardsMouse = mousePositionInWorld - objectPositionXY;
float distanceXY = vector2TowardsMouse.magnitude;
if (distanceXY <= DistanceThreshold)
{
// Stop the object because it's already close enough to the mouse.
rb.velocity = Vector3.zero;
}
else
{
// Move the object towards the mouse.
// Note: velocity.z will be 0
rb.velocity = vector2TowardsMouse.normalized * speed;
}
}