Advertisement
Diamond32_Tutoriales

FPS Controller

Aug 16th, 2023
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5.  
  6.  
  7.  
  8. public class PlayerController : MonoBehaviour
  9. {
  10. public float walkingSpeed = 7.5f;
  11. public float runningSpeed = 11.5f;
  12. public float jumpSpeed = 8.0f;
  13. public float gravity = 20.0f;
  14. public Camera playerCamera;
  15. public float lookSpeed = 2.0f;
  16. public float lookXLimit = 45.0f;
  17.  
  18. CharacterController characterController;
  19. Vector3 moveDirection = Vector3.zero;
  20. float rotationX = 0;
  21.  
  22. [HideInInspector]
  23. public bool canMove = true;
  24.  
  25. void Start()
  26. {
  27. characterController = GetComponent<CharacterController>();
  28. }
  29.  
  30. void Update()
  31. {
  32. Vector3 forward = transform.TransformDirection(Vector3.forward);
  33. Vector3 right = transform.TransformDirection(Vector3.right);
  34. bool isRunning = Input.GetKey(KeyCode.LeftShift);
  35. float curSpeedX = canMove ? (isRunning ? runningSpeed : walkingSpeed) * Input.GetAxis("Vertical") : 0;
  36. float curSpeedY = canMove ? (isRunning ? runningSpeed : walkingSpeed) * Input.GetAxis("Horizontal") : 0;
  37. float movementDirectionY = moveDirection.y;
  38. moveDirection = (forward * curSpeedX) + (right * curSpeedY);
  39.  
  40. if (Input.GetButton("Jump") && canMove && characterController.isGrounded)
  41. {
  42. moveDirection.y = jumpSpeed;
  43. }
  44. else
  45. {
  46. moveDirection.y = movementDirectionY;
  47. }
  48.  
  49. if (!characterController.isGrounded)
  50. {
  51. moveDirection.y -= gravity * Time.deltaTime;
  52. }
  53.  
  54. characterController.Move(moveDirection * Time.deltaTime);
  55.  
  56. if (canMove)
  57. {
  58. rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
  59. rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
  60. playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
  61. transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
  62. }
  63. }
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement