1
\$\begingroup\$

I'm trying to create a camera like in Fortnite or Gears of War. It's focus must be to the right side from the character:enter image description here

But when I rotate the camera, the character slightly shivers. Lerping and multiplying by Time.deltatTime doesn't help.

This is my code:

    using UnityEngine;

    [RequireComponent(typeof(Camera))]

    public class ThirdPersonCamera : MonoBehaviour
    {
        [Header("Sensitivity")]
        [SerializeField] private float xSensitivity;
        [SerializeField] private float ySensitivity;

    [Header("Limit angles")]
    [SerializeField] private float upLimit;
    [SerializeField] private float downLimit;

    [Header("Positioning")]
    [SerializeField] private Vector3 offset;
    [SerializeField] private float maxDistanceFromPlayer;
    [SerializeField] private Transform player;

    private float rotationAboutX;
    private float rotationAboutY;

    // Start is called before the first frame update
    void Start()
    {
        rotationAboutX = transform.localEulerAngles.x;
        rotationAboutY = transform.localEulerAngles.y;
    }

    void Update()
    {
        rotationAboutX -= Input.GetAxis("Mouse Y") * ySensitivity;
        rotationAboutY += Input.GetAxis("Mouse X") * xSensitivity;

        rotationAboutX = Mathf.Clamp(rotationAboutX, downLimit, upLimit);
    }

    // Adjust camera position.
    void LateUpdate()
    {
        Vector3 direction = new Vector3(0.0f, 0.0f, -maxDistanceFromPlayer);
        Quaternion rotation = Quaternion.Euler(rotationAboutX, rotationAboutY, 0);
        // Point to look at in the runitme.
        Vector3 focus = player.position + transform.TransformDirection(offset);

        // Rotate vector according to mouse inputs.
        transform.position = focus + rotation * direction;

        transform.LookAt(focus);
    }
}

It shivers only if offset is not zero. Otherwise it's ok.

\$\endgroup\$
  • 1
    \$\begingroup\$ You have a feedback loop here: the current rotation changes focus, and focus changes the current rotation, which means you compute a different focus next frame, which means you compute a different rotation, which means... \$\endgroup\$ – DMGregory Jan 16 at 18:50
1
\$\begingroup\$

I have solved the problem. It was enough to use this simple code instead of computing focus manually:

transform.LookAt(player.position);
transform.Translate(offset, transform);
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.