CameraManager.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using Cinemachine;
  4. using UnityEngine;
  5. using UnityEngine.InputSystem;
  6. public class CameraManager : MonoBehaviour {
  7. [SerializeField] private float speed;
  8. [SerializeField] private float maxSpeed = 5f;
  9. [SerializeField] private float acceleration = 10f;
  10. [SerializeField] private float damping = 15f;
  11. [SerializeField] private CinemachineVirtualCamera camera;
  12. RoomBuilder roomBuilder;
  13. InputAction movement;
  14. Transform cameraTransform;
  15. private Vector3 lastPosition;
  16. private Vector3 horizontalVelocity;
  17. private Vector3 targetPosition;
  18. private void Awake() {
  19. roomBuilder = new RoomBuilder();
  20. cameraTransform = camera.transform;
  21. }
  22. private void OnEnable() {
  23. cameraTransform.LookAt(this.transform);
  24. lastPosition = this.transform.position;
  25. movement = roomBuilder.Camera.Movement;
  26. roomBuilder.Camera.Enable();
  27. }
  28. private void OnDisable() {
  29. roomBuilder.Camera.Disable();
  30. }
  31. private Vector3 GetCameraForward() {
  32. Vector3 forward = cameraTransform.forward;
  33. forward.y = 0f;
  34. return forward;
  35. }
  36. private Vector3 GetCameraRight() {
  37. Vector3 right = cameraTransform.right;
  38. right.y = 0f;
  39. return right;
  40. }
  41. private void UpdateVelocity() {
  42. horizontalVelocity = (this.transform.position - lastPosition) / Time.deltaTime;
  43. horizontalVelocity.y = 0;
  44. lastPosition = this.transform.position;
  45. }
  46. private void GetKeyboardMovement() {
  47. Vector3 inputValue = movement.ReadValue<Vector2>().x * GetCameraRight() + movement.ReadValue<Vector2>().y * GetCameraForward();
  48. inputValue = inputValue.normalized;
  49. if (inputValue.sqrMagnitude > 0.1f) {
  50. targetPosition = inputValue;
  51. }
  52. }
  53. private void UpdateBasePosition() {
  54. if (targetPosition.sqrMagnitude > 0.1f) {
  55. speed = Mathf.Lerp(speed, maxSpeed, Time.deltaTime * acceleration);
  56. transform.position += targetPosition * speed * Time.deltaTime;
  57. } else {
  58. horizontalVelocity = Vector3.Lerp(horizontalVelocity, targetPosition, Time.deltaTime * damping);
  59. transform.position += horizontalVelocity * Time.deltaTime;
  60. }
  61. targetPosition = Vector3.zero;
  62. }
  63. private void Update() {
  64. GetKeyboardMovement();
  65. UpdateVelocity();
  66. UpdateBasePosition();
  67. }
  68. }