ambrose01

FirstPersonController.cs

Oct 21st, 2025
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.87 KB | Source Code | 0 0
  1. using UnityEngine;
  2.  
  3. [RequireComponent(typeof(CharacterController))]
  4. public class FirstPersonController : MonoBehaviour
  5. {
  6.     [Header("Movement Settings")]
  7.     public float moveSpeed = 5f;
  8.     public float jumpHeight = 1.5f;
  9.     public float gravity = -9.81f;
  10.  
  11.     [Header("Mouse Look Settings")]
  12.     public float mouseSensitivity = 100f;
  13.     public Transform playerCamera;
  14.     private float xRotation = 0f;
  15.  
  16.     private CharacterController controller;
  17.     private Vector3 velocity;
  18.     private bool isGrounded;
  19.  
  20.     void Start()
  21.     {
  22.         controller = GetComponent<CharacterController>();
  23.         Cursor.lockState = CursorLockMode.Locked; // Hides cursor
  24.     }
  25.  
  26.     void Update()
  27.     {
  28.         HandleMovement();
  29.         HandleMouseLook();
  30.     }
  31.  
  32.     void HandleMovement()
  33.     {
  34.         isGrounded = controller.isGrounded;
  35.  
  36.         if (isGrounded && velocity.y < 0)
  37.         {
  38.             velocity.y = -2f; // Small downward force to stick to ground
  39.         }
  40.  
  41.         float x = Input.GetAxis("Horizontal");
  42.         float z = Input.GetAxis("Vertical");
  43.  
  44.         Vector3 move = transform.right * x + transform.forward * z;
  45.         controller.Move(move * moveSpeed * Time.deltaTime);
  46.  
  47.         if (Input.GetButtonDown("Jump") && isGrounded)
  48.         {
  49.             velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
  50.         }
  51.  
  52.         velocity.y += gravity * Time.deltaTime;
  53.         controller.Move(velocity * Time.deltaTime);
  54.     }
  55.  
  56.     void HandleMouseLook()
  57.     {
  58.         float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
  59.         float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
  60.  
  61.         xRotation -= mouseY;
  62.         xRotation = Mathf.Clamp(xRotation, -90f, 90f);
  63.  
  64.         playerCamera.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
  65.         transform.Rotate(Vector3.up * mouseX);
  66.     }
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment