using System.Collections; using System.Collections.Generic; using UnityEngine; public class FPSController : MonoBehaviour { // Variables to control movement behavior public float walkingSpeed = 7.5f; public float runningSpeed = 11.5f; public float jumpSpeed = 8.0f; public float gravity = 20.0f; // Variables to control camera look public Camera playerCamera; public float lookSpeed = 2.0f; public float lookXLimit = 45.0f; // Variables to retain player state private CharacterController characterController; private Vector3 moveDirection = Vector3.zero; private float rotationX = 0; [HideInInspector] public bool canMove = true; void Start() { // Latch onto existing player controller characterController = GetComponent(); // Lock the cursor in the view and hide it Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } void Update() { // Recalculate move direction based on player axes Vector3 forward = transform.TransformDirection(Vector3.forward); Vector3 right = transform.TransformDirection(Vector3.right); // Store existing jump/fall movement float currentSpeedY = moveDirection.y; // Press Left Shift to run bool isRunning = Input.GetKey(KeyCode.LeftShift); // Assume x and z speeds are 0 float speedX = 0; float speedZ = 0; float currentSpeed = 0; // Calculate the speed if the player can move if(canMove) { // Decide whether to use running or walking speed if(isRunning) { currentSpeed = runningSpeed; } else { currentSpeed = walkingSpeed; } speedX = currentSpeed * Input.GetAxis("Vertical"); speedZ = currentSpeed * Input.GetAxis("Horizontal"); } // Create movement horizontal movement vector (X and Z axes) moveDirection = (forward * speedX) + (right * speedZ); // Set vertical movement (Y axis) if(Input.GetButton("Jump") && canMove && characterController.isGrounded) { moveDirection.y = jumpSpeed; } else { moveDirection.y = currentSpeedY; } // Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below // when the moveDirection is multiplied by deltaTime). This is because gravity should be applied // as an acceleration (meters / second^2) if(!characterController.isGrounded) { moveDirection.y -= gravity * Time.deltaTime; } // Actually move the controller characterController.Move(moveDirection * Time.deltaTime); // Rotate the player and camera. The player spins and the camera looks up or down. if(canMove) { rotationX += -Input.GetAxis("Mouse Y") * lookSpeed; rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit); playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0); transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0); } } }