plastic_fps_controller.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. using System;
  2. using UnityEngine;
  3. public class plastic_fps_controller : MonoBehaviour
  4. {
  5. [SerializeField] private float speed = 5.0f;
  6. [SerializeField] private float mouseSensitivity = 3.5f;
  7. private float _cameraPitch = 0.0f;
  8. private float _cameraYaw = 0.0f;
  9. private bool _isCursorLocked = false;
  10. private void Start()
  11. {
  12. }
  13. // Update is called once per frame
  14. void Update()
  15. {
  16. if (Input.GetMouseButtonDown(1))
  17. {
  18. SetCursorLock(true);
  19. _isCursorLocked = true;
  20. }
  21. else if (Input.GetKeyDown(KeyCode.Escape))
  22. {
  23. if (_isCursorLocked)
  24. {
  25. SetCursorLock(false);
  26. _isCursorLocked = false;
  27. }
  28. else
  29. Application.Quit(0);
  30. }
  31. if (_isCursorLocked)
  32. {
  33. UpdateRotation();
  34. UpdatePosition();
  35. }
  36. }
  37. void UpdateRotation()
  38. {
  39. Vector2 targetMousePos = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
  40. _cameraPitch = -targetMousePos.y * mouseSensitivity;
  41. _cameraYaw = targetMousePos.x * mouseSensitivity;
  42. transform.eulerAngles += new Vector3(_cameraPitch, _cameraYaw, 0.0f);
  43. }
  44. void UpdatePosition()
  45. {
  46. // Calculate movement distance
  47. float movementDistance = speed * Time.deltaTime;
  48. if (Input.GetKey(KeyCode.LeftShift))
  49. {
  50. movementDistance *= 2.0f;
  51. }
  52. if (Input.GetKey(KeyCode.LeftControl))
  53. {
  54. movementDistance /= 5.0f;
  55. }
  56. Vector3 movement = Vector3.zero;
  57. if (Input.GetKey(KeyCode.A))
  58. {
  59. movement.x = -movementDistance;
  60. }
  61. if (Input.GetKey(KeyCode.D))
  62. {
  63. movement.x = movementDistance;
  64. }
  65. if (Input.GetKey(KeyCode.W))
  66. {
  67. movement.z = movementDistance;
  68. }
  69. if (Input.GetKey(KeyCode.S))
  70. {
  71. movement.z = -movementDistance;
  72. }
  73. if (Input.GetKey(KeyCode.Q))
  74. {
  75. movement.y = movementDistance;
  76. }
  77. if (Input.GetKey(KeyCode.E))
  78. {
  79. movement.y = -movementDistance;
  80. }
  81. transform.position += transform.rotation * movement;
  82. }
  83. private void OnDestroy()
  84. {
  85. SetCursorLock(false);
  86. }
  87. private void SetCursorLock(bool lockCursor) {
  88. if (lockCursor) {
  89. Cursor.lockState = CursorLockMode.Locked;
  90. Cursor.visible = false;
  91. } else {
  92. Cursor.lockState = CursorLockMode.None;
  93. Cursor.visible = true;
  94. }
  95. }
  96. }
粤ICP备19079148号