How to Interpolate correctly the rotation when using Cinemachine Third Person Follow Mode
Cinemachine has released a third person follow mode in the latest version, and the Unity education team has made a tutorial on youtube to teach how to use it.
Unfortunatley, they haven't provided the project nor the script files for the video. But they explain and show part of the code to control the camera. I managed to reproduce the part of the video that interests me, the rotation around a character and making the character align with the camera's orientation when it starts moving. I'm not interested in the aiming part.
The problem I have, which also happens in the tutorial video (you can see this around 3:35), is that the character aligns instantaneously with the camera when you start moving it. I tried to use Quaternion.Slerp but it's not working.
Any suggestion to fix this problem?
My code is bellow (the original line from the video is commented inside the if (v != 0) block).
using UnityEngine;
public class ThirdPersonCameraController : MonoBehaviour
{
public Transform cameraPivot;
public float rotationSpeed = 4;
public float rotationLerp = 2;
private Transform myTransform;
public void Start()
{
myTransform = GetComponent<Transform>();
}
public void Update()
{
float v = Input.GetAxis("Vertical");
float yaw = Input.GetAxis("Mouse X");
float pitch = Input.GetAxis("Mouse Y");
// Camera Vertical Rotation
cameraPivot.rotation *= Quaternion.AngleAxis(yaw * rotationSpeed, Vector3.up);
// Camera Horizontal Rotation
cameraPivot.rotation *= Quaternion.AngleAxis(pitch * rotationSpeed, Vector3.right);
// Limit the angles
Vector3 angles = cameraPivot.localEulerAngles;
angles.z = 0F;
float angle = cameraPivot.localEulerAngles.x;
if (angle > 180 && angle < 340)
{
angles.x = 340;
}
else if (angle < 180 && angle > 40)
{
angles.x = 40;
}
cameraPivot.localEulerAngles = angles;
// If Character is moving, align it with the camera's orientation
if (v != 0)
{
Quaternion rot = Quaternion.Slerp(myTransform.rotation, cameraPivot.rotation, Time.deltaTime * rotationLerp);
rot.eulerAngles = new Vector3(0, rot.eulerAngles.y, 0);
myTransform.rotation = Quaternion.Euler(0, rot.eulerAngles.y, 0);
//myTransform.rotation = Quaternion.Euler(0, cameraPivot.eulerAngles.y, 0);
cameraPivot.localEulerAngles = new Vector3(angles.x, 0, 0);
}
}
}