I have a script that makes my camera rotate around a target when right click is pressed. Currently, when the right click is released, the rotation comes to a full stop, which is fully expected behavior. I want it to keep rotating for a little while after the mouse button is up, before it comes to a full stop, like if it was decelerating. Here is the code that handles the rotation around the given target:
if (!target)
return;
if (Input.GetMouseButtonDown(1))
previousPosition = cam.ScreenToViewportPoint(Input.mousePosition);
if (Input.GetMouseButton(1))
{
Vector3 nextDirection = previousPosition - cam.ScreenToViewportPoint(Input.mousePosition);
direction = Vector3.SmoothDamp(direction, nextDirection, ref smoothVelocity, smoothTime);
cam.transform.position = target.position;
cam.transform.Rotate(new Vector3(1, 0, 0), direction.y * 180);
cam.transform.Rotate(new Vector3(0, 1, 0), -direction.x * 180, Space.World);
cam.transform.Translate(new Vector3(0, 0, -distanceFromSphere));
previousPosition = cam.ScreenToViewportPoint(Input.mousePosition);
}
Here are the needed references:
public Camera cam;
public Vector3 previousPosition;
public Transform target;
public float distanceFromSphere = 100;
public Vector3 direction;
public Vector3 smoothVelocity = Vector3.zero;
public float smoothTime = 3f;
Is there a way to make the camera rotation be accelerated when the mouse button is down, and when the mouse is up, to be decelerated?
CodePudding user response:
You can use Vector3.Lerp, you can find more on it here - https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html
CodePudding user response:
What you need is inertia, get the Rotate and Translate calls outside the if statement, and at the end multiply the direction with 0.98 or 0.99 depending on how much intertia you need.
public float inertia = 0.98f;
direction *= inertia;