Advertisement
Diamond32_Tutoriales

FPSController

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