I'm trying to write a camera script in Unity that would smoothly rotate the camera over time towards the desired rotation, with separate input parameters for yaw, pitch and roll smoothing, and I can't figure out how to do it properly. That camera would be meant to follow a vehicle that can move and rotate in 3D space. I've tried many things, most recently the code below:
Vector3 targetLookDirection = (lookTarget - cameraPosition).normalized;
Quaternion targetCameraRotation = Quaternion.LookRotation(targetLookDirection, vehicleTransform.up);
Vector3 currentDeviation = (transform.rotation * Quaternion.Inverse(targetRotation)).eulerAngles;
//since deviation * target = current, then deviation = current * inv(target)
Vector3 newDeviation = new Vector3
{
x = Mathf.SmoothDampAngle(currentDeviation.x, 0f, ref pitchVelocity, pitchSmoothTime),
y = Mathf.SmoothDampAngle(currentDeviation.y, 0f, ref yawVelocity, yawSmoothTime),
z = Mathf.SmoothDampAngle(currentDeviation.z, 0f, ref rollVelocity, rollSmoothTime)
};
transform.rotation = targetRotation;
transform.Rotate(newDeviation);
where lookTarget
and cameraPosition
are Vector3s, and transform
refers to the camera transform since the script is attached to the camera Game Object. The code is in LateUpdate()
.
The code looks logical to me, but in reality when I run it with the Smooth Times
set to around 0.25 the camera just shakes chaotically. The shaking behaviour is also different depending on which way I look in 3D space (with visibly different behaviour when looking towards z+ direction), which is weird to me since the smoothing is only working with relative rotation of the camera from the target rotation, and not their world rotations.
I would very much appreciate it if you could let me know how to fix this script to make it work properly.