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

public class CameraHandler : MonoBehaviour
{

    public Transform Target;
    public float Sensitivity = 1f;
    public Vector2 _lastMousePos;

    Quaternion TargetRotation;
    Vector3 TargetPosition;
    void Start()
    {
        _lastMousePos = Input.mousePosition;
        TargetRotation = Target.rotation;
        TargetPosition = Target.position;
        transform.LookAt(Target);
    }

    void Update()
    {
        var mousePos = (Vector2)Input.mousePosition;
        if (!Input.GetMouseButton(0))
        {
            var delta = (mousePos - _lastMousePos) * Sensitivity;

            var locRot = TargetRotation.eulerAngles;
            var pos = TargetPosition;

            locRot.x -= delta.y;
            locRot.y += delta.x;
            if (locRot.x > 30 && locRot.x < 180) locRot.x = 30;

            pos.x += -delta.x * .05f;
            pos.y += delta.y * .05f;

            TargetRotation = Quaternion.Slerp(Target.rotation, Quaternion.Euler(locRot), Time.deltaTime);
            TargetPosition = Vector3.Lerp(Target.position, pos, Time.deltaTime);
        }
        _lastMousePos = mousePos;
    }

    void LateUpdate()
    {
        Target.rotation = Quaternion.Slerp(Target.rotation, TargetRotation, Time.deltaTime);
        Target.position = Vector3.Lerp(Target.position, TargetPosition, Time.deltaTime);
        transform.LookAt(Target);
    }
}
