Hello,
I have written a smooth vehicle-following camera, but for some reason, it is shaky, like it was not updated often enough.
I’ve read several questions about this. Some people suggest to use LateUpdate() instead of Update(). I did this, but the problem remains. Some other people suggest to use FixedUpdate(). I tried that too, and it worked, but I’m afraid using FixedUpdate() is only hiding the problem without actually fixing it.
I saw in the scene view that the car itself was shaky, not the camera. Also when I drive, everything around me (objects, shadows, etc) are moving (relatively to the camera) smoothly. It’s only the followed vehicle itself that is shaky (relatively to the camera only). I tried using a simple sphere instead of a complete car instead to make sure the complexity of the car model wasn’t causing this, but I had the same problem. So I’m not sure about what is wrong.
Here is my code :
using UnityEngine;
public class RaceCameraController : MonoBehaviour
{
/// <summary>
/// Vehicle to look at.
/// </summary>
[Tooltip("Vehicle to look at.")]
public GameObject car;
/// <summary>
/// X rotation angle of the camera, relatively to the vehicle.
/// </summary>
[Tooltip("X rotation angle of the camera, relatively to the vehicle.")]
public float lookXAngle;
/// <summary>
/// Position the camera tries to reach progressively, relatively to the vehicle.
/// </summary>
[Tooltip("Position the camera tries to reach progressively, relatively to the vehicle.")]
public Vector3 carRelativeTargetPosition;
/// <summary>
/// Duration, in seconds, it would take the camera to reach its target position if the vehicle
/// immediately stopped.
/// </summary>
[Tooltip("Duration, in seconds, it would take the camera to reach its target position if the vehicle immediately stopped.")]
public float repositioningDuration;
void LateUpdate()
{
Vector3 targetPosition = car.transform.TransformPoint(carRelativeTargetPosition);
Quaternion targetRotation = car.transform.rotation * Quaternion.Euler(lookXAngle, 0f, 0f);
float progress = Mathf.Min(Time.deltaTime / repositioningDuration, 1.0f);
transform.position = Vector3.Lerp(gameObject.transform.position, targetPosition, progress);
transform.rotation = Quaternion.SlerpUnclamped(transform.rotation, targetRotation, progress);
}
}
Do you have any idea about what could be wrong ? Thanks.