FPSController.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace TobyFredson
  5. {
  6. [RequireComponent(typeof(CharacterController))]
  7. public class FPSController : MonoBehaviour
  8. {
  9. public Camera playerCamera;
  10. public float walkSpeed = 6f;
  11. public float runSpeed = 12f;
  12. public float jumpPower = 7f;
  13. public float gravity = 10f;
  14. public float lookSpeed = 2f;
  15. public float lookXLimit = 45f;
  16. Vector3 moveDirection = Vector3.zero;
  17. float rotationX = 0;
  18. public bool canMove = true;
  19. CharacterController characterController;
  20. void Start()
  21. {
  22. characterController = GetComponent<CharacterController>();
  23. Cursor.lockState = CursorLockMode.Locked;
  24. Cursor.visible = false;
  25. }
  26. void Update()
  27. {
  28. #region Handles Movment
  29. Vector3 forward = transform.TransformDirection(Vector3.forward);
  30. Vector3 right = transform.TransformDirection(Vector3.right);
  31. // Press Left Shift to run
  32. bool isRunning = Input.GetKey(KeyCode.LeftShift);
  33. float curSpeedX = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Vertical") : 0;
  34. float curSpeedY = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Horizontal") : 0;
  35. float movementDirectionY = moveDirection.y;
  36. moveDirection = (forward * curSpeedX) + (right * curSpeedY);
  37. #endregion
  38. #region Handles Jumping
  39. if (Input.GetButton("Jump") && canMove && characterController.isGrounded)
  40. {
  41. moveDirection.y = jumpPower;
  42. }
  43. else
  44. {
  45. moveDirection.y = movementDirectionY;
  46. }
  47. if (!characterController.isGrounded)
  48. {
  49. moveDirection.y -= gravity * Time.deltaTime;
  50. }
  51. #endregion
  52. #region Handles Rotation
  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. #endregion
  62. }
  63. }
  64. }