Thirdperson Camera

Jittering Camera Issue
mail@pastecode.io avatar
unknown
csharp
2 years ago
1.8 kB
4
Indexable
Never
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Camera_Follow : MonoBehaviour
{
    private Transform target;

    public float mouseSensitivity = 1;
    public Vector2 lookDistance = new Vector2(0.5f, 10);
    private float mouseX, mouseY;

    private float currentDistance;

    public LayerMask obstacle;

    private void Awake()
    {
        SetTarget();
    }

    private void Start()
    {
        currentDistance = lookDistance.y;
    }

    private void Update()
    {
        mouseX += Input.GetAxis("Mouse X") * mouseSensitivity;
        mouseY -= Input.GetAxis("Mouse Y") * mouseSensitivity;
        mouseY = Mathf.Clamp(mouseY, -60, 0);
    }

    private void FixedUpdate()
    {
        Vector3 cameraPosition = new Vector3(0, 0, currentDistance);
        Quaternion rotation = Quaternion.Euler(mouseY, mouseX, 0);
        transform.position = Vector3.Lerp(transform.position, target.position + rotation * cameraPosition, 2.5f * Time.fixedDeltaTime);

        RaycastHit myHit;
        cameraIsColliding(out myHit);

        if (cameraIsColliding(out myHit))
        {
            currentDistance = Mathf.Clamp(myHit.distance, lookDistance.x, lookDistance.y);
        }

        else
        {
            currentDistance = lookDistance.y;
        }

        transform.LookAt(target);
    }

    public void SetTarget()
    {
        if(target == null)
        {
            target = GameObject.FindGameObjectWithTag("Player").transform.Find("LookAtTarget").transform;
        }
    }

    bool cameraIsColliding(out RaycastHit hit)
    {
        return Physics.Raycast(target.position, transform.position, out hit);
    }
}