Advertisement
7889

Untitled

Oct 7th, 2023
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.22 KB | Gaming | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. [RequireComponent(typeof(CharacterController))]
  6. public class PlayerMovement : MonoBehaviour
  7. {
  8.     [Header("Movement Settings")]
  9.     public float walkSpeed = 5f;
  10.     public float sprintSpeed = 10f;
  11.     public float crouchSpeed = 2f;
  12.     public float jumpForce = 8f;
  13.     public float gravity = 20f;
  14.  
  15.     [Header("Crouch Settings")]
  16.     public Transform playerCamera;
  17.     public float standingHeight = 2f;
  18.     public float crouchingHeight = 1f;
  19.  
  20.     private CharacterController controller;
  21.     private bool isCrouching = false;
  22.     private bool isSprinting = false;
  23.     private Vector3 moveDirection = Vector3.zero;
  24.  
  25.     private void Start()
  26.     {
  27.         controller = GetComponent<CharacterController>();
  28.         Cursor.lockState = CursorLockMode.Locked;
  29.         Cursor.visible = false;
  30.     }
  31.  
  32.     private void Update()
  33.     {
  34.         HandleMovementInput();
  35.         HandleCrouchInput();
  36.     }
  37.  
  38.     private void HandleMovementInput()
  39.     {
  40.         float moveSpeed = isCrouching ? crouchSpeed : (isSprinting ? sprintSpeed : walkSpeed);
  41.  
  42.         float horizontalInput = Input.GetAxis("Horizontal");
  43.         float verticalInput = Input.GetAxis("Vertical");
  44.  
  45.         Vector3 inputDirection = transform.TransformDirection(new Vector3(horizontalInput, 0f, verticalInput));
  46.         moveDirection = inputDirection.normalized * moveSpeed;
  47.  
  48.         if (controller.isGrounded)
  49.         {
  50.             if (Input.GetButtonDown("Jump"))
  51.             {
  52.                 moveDirection.y = jumpForce;
  53.             }
  54.         }
  55.  
  56.         moveDirection.y -= gravity * Time.deltaTime;
  57.         controller.Move(moveDirection * Time.deltaTime);
  58.     }
  59.  
  60.     private void HandleCrouchInput()
  61.     {
  62.         if (Input.GetButtonDown("Fire2"))
  63.         {
  64.             isCrouching = !isCrouching;
  65.             float targetHeight = isCrouching ? crouchingHeight : standingHeight;
  66.             playerCamera.localPosition = new Vector3(0f, targetHeight, 0f);
  67.         }
  68.  
  69.         if (Input.GetButtonDown("Fire1"))
  70.         {
  71.             isSprinting = true;
  72.         }
  73.  
  74.         if (Input.GetButtonUp("Fire1"))
  75.         {
  76.             isSprinting = false;
  77.         }
  78.     }
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement