Third person camera script

I am VERY new to this programming thing, I have done some basic code for character movement and this code I am going to share is for the third person camera, I want to implement things like the camera tends to be behind the player while the mouse is not moving and, if the camera has been moved by the mouse and after a couple of seconds, if there is no mouse movement, the camera tends to go back to the position behind the player, something like what happens in RDR2.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ThirdPersonCamera : MonoBehaviour
{
    public Transform target;
    public float distance = 3.5f;
    public float sensitivity = 3f;
    public float minY = -60f;
    public float maxY = 85f;

    private float currentX = 0f;
    private float currentY = 0f;

    void LateUpdate()
    {
        currentX += Input.GetAxis("Mouse X") * sensitivity;
        currentY -= Input.GetAxis("Mouse Y") * sensitivity;

        currentY = Mathf.Clamp(currentY, minY, maxY);

        Vector3 cameraPosition = new(0, 0, -distance);
        Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
        transform.position = target.position + rotation * cameraPosition;

        transform.LookAt(target);
    }
}

I would appreciate if you could share ideas to do this and improvements to the code.

Cinemachine has a built-in third person mode with all aspects covered. Don’t waste time writing your own. :wink:

2 Likes

thanks!!