using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; public class PlayerCameraController : MonoBehaviour, PlayerInput.ICameraActions { // REFERENCES public Camera cam; public Transform player; // PARAMETERS public AnimationCurve pitchCamHeightCurve; public Vector2 pitchExtents; public AnimationCurve pitchCamDistCurve; public float cameraSmoothing; public Vector2 cameraSensitivity; public Vector2 cameraInvert; // INTERNAL private PlayerInput _inpt = null; private Vector2 _curLookInpt = Vector2.zero; private Vector2 _smoothLookInpt = Vector2.zero; private Vector3 _curCamRot = Vector3.zero; // LIFECYCLE private void Awake() { this._curCamRot = this.transform.eulerAngles; Debug.Log(this.cam.projectionMatrix.ToString()); } private void OnEnable() { if (this._inpt == null) { this._inpt = new PlayerInput(); this._inpt.Camera.SetCallbacks(this); } this._inpt.Enable(); Cursor.lockState = CursorLockMode.Locked; Cursor.visible = true; } private void OnDisable() { if (this._inpt != null) { this._inpt.Disable(); } Cursor.lockState = CursorLockMode.None; } private void LateUpdate() { this.HandleInput(); this.PlaceCamera(); } // BEHAVIORS private void HandleInput() { // Smooth input this._smoothLookInpt = MathExtras.LerpSmooth2(this._smoothLookInpt, MathExtras.ClipVec2(this._curLookInpt, 1f), Time.deltaTime, this.cameraSmoothing); // Clip Input if (this._curLookInpt.sqrMagnitude < 1e-3f && this._smoothLookInpt.sqrMagnitude < 1e-3f) this._smoothLookInpt = Vector2.zero; } private void PlaceCamera() { // Apply sensitivity and inversion to input Vector2 inputDir = Vector2.Scale(Vector2.Scale(this._smoothLookInpt, this.cameraSensitivity), this.cameraInvert); // Update camera rotation this._curCamRot += new Vector3(inputDir.y, inputDir.x, 0f); // Clamp camera pitch if (this._curCamRot.x > 180f) this._curCamRot.x = this._curCamRot.x - 360f; this._curCamRot.x = Mathf.Clamp(this._curCamRot.x, this.pitchExtents.x, this.pitchExtents.y); // Zero out camera roll this._curCamRot.z = 0f; // Apply rotation this.transform.eulerAngles = this._curCamRot; // Get current pitch relative to extents float relPitch = Mathf.InverseLerp(this.pitchExtents.x, this.pitchExtents.y, this._curCamRot.x); // Place relative to player this.transform.position = this.player.transform.position + (Vector3.up * this.pitchCamHeightCurve.Evaluate(relPitch)); // Determine camera distance this.cam.transform.localPosition = Vector3.back * this.pitchCamDistCurve.Evaluate(relPitch); } // INPUT public void OnLookInput(InputAction.CallbackContext context) { this._curLookInpt = context.ReadValue(); } }