ThirdPersonCam.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using UnityEngine;
  2. public class ThirdPersonCam : MonoBehaviour
  3. {
  4. [Header("References")]
  5. public Transform orientation;
  6. public Transform player;
  7. public Transform playerObj;
  8. public Rigidbody rb;
  9. public float rotationSpeed;
  10. private void Start()
  11. {
  12. Cursor.lockState = CursorLockMode.Locked;
  13. Cursor.visible = false;
  14. rb.freezeRotation = true;
  15. }
  16. private void Update()
  17. {
  18. // -------- Camera → Orientation (Y-axis only) --------
  19. Vector3 viewDir = player.position - transform.position;
  20. viewDir.y = 0f;
  21. orientation.forward = viewDir.normalized;
  22. // -------- Player Rotation --------
  23. float horizontalInput = Input.GetAxis("Horizontal");
  24. float verticalInput = Input.GetAxis("Vertical");
  25. Vector3 inputDir = orientation.forward * verticalInput + orientation.right * horizontalInput;
  26. inputDir.y = 0f; // EXTRA SAFETY
  27. if (inputDir.sqrMagnitude > 0.01f)
  28. {
  29. Quaternion targetRotation = Quaternion.LookRotation(inputDir);
  30. playerObj.rotation = Quaternion.Slerp(
  31. playerObj.rotation,
  32. targetRotation,
  33. rotationSpeed * Time.deltaTime
  34. );
  35. }
  36. }
  37. }