fxvFPSController.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace FXV.FogDemo
  5. {
  6. public class fxvFPSController : MonoBehaviour
  7. {
  8. public Camera playerCamera;
  9. float lookSpeed = 2.0f;
  10. float lookXLimit = 45.0f;
  11. [SerializeField]
  12. float walkingSpeed = 7.5f;
  13. [SerializeField]
  14. float runningSpeed = 11.5f;
  15. [SerializeField]
  16. float gravity = 20.0f;
  17. CharacterController characterController;
  18. Vector3 moveDirection = Vector3.zero;
  19. float rotationX = 0;
  20. [HideInInspector]
  21. bool canMove = true;
  22. void Start()
  23. {
  24. characterController = GetComponent<CharacterController>();
  25. Cursor.lockState = CursorLockMode.Locked;
  26. Cursor.visible = false;
  27. }
  28. void Update()
  29. {
  30. Vector3 forward = transform.TransformDirection(Vector3.forward);
  31. Vector3 right = transform.TransformDirection(Vector3.right);
  32. bool isRunning = Input.GetKey(KeyCode.LeftShift);
  33. float curSpeedX = canMove ? (isRunning ? runningSpeed : walkingSpeed) * Input.GetAxis("Vertical") : 0;
  34. float curSpeedY = canMove ? (isRunning ? runningSpeed : walkingSpeed) * Input.GetAxis("Horizontal") : 0;
  35. float movementDirectionY = moveDirection.y;
  36. moveDirection = (forward * curSpeedX) + (right * curSpeedY);
  37. if (Input.GetKey(KeyCode.E) && canMove)
  38. {
  39. moveDirection.y = walkingSpeed;
  40. }
  41. else if (Input.GetKey(KeyCode.Q) && canMove)
  42. {
  43. moveDirection.y = -walkingSpeed;
  44. }
  45. else
  46. {
  47. moveDirection.y = 0.0f;
  48. }
  49. if (!characterController.isGrounded)
  50. {
  51. moveDirection.y -= gravity * Time.deltaTime;
  52. }
  53. characterController.Move(moveDirection * Time.deltaTime);
  54. if (canMove)
  55. {
  56. rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
  57. rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
  58. playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
  59. transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
  60. }
  61. }
  62. }
  63. }