Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- [RequireComponent(typeof(CharacterController))]
- public class PlayerMovement : MonoBehaviour
- {
- [Header("Movement Settings")]
- public float walkSpeed = 5f;
- public float sprintSpeed = 10f;
- public float crouchSpeed = 2f;
- public float jumpForce = 8f;
- public float gravity = 20f;
- [Header("Crouch Settings")]
- public Transform playerCamera;
- public float standingHeight = 2f;
- public float crouchingHeight = 1f;
- private CharacterController controller;
- private bool isCrouching = false;
- private bool isSprinting = false;
- private Vector3 moveDirection = Vector3.zero;
- private void Start()
- {
- controller = GetComponent<CharacterController>();
- Cursor.lockState = CursorLockMode.Locked;
- Cursor.visible = false;
- }
- private void Update()
- {
- HandleMovementInput();
- HandleCrouchInput();
- }
- private void HandleMovementInput()
- {
- float moveSpeed = isCrouching ? crouchSpeed : (isSprinting ? sprintSpeed : walkSpeed);
- float horizontalInput = Input.GetAxis("Horizontal");
- float verticalInput = Input.GetAxis("Vertical");
- Vector3 inputDirection = transform.TransformDirection(new Vector3(horizontalInput, 0f, verticalInput));
- moveDirection = inputDirection.normalized * moveSpeed;
- if (controller.isGrounded)
- {
- if (Input.GetButtonDown("Jump"))
- {
- moveDirection.y = jumpForce;
- }
- }
- moveDirection.y -= gravity * Time.deltaTime;
- controller.Move(moveDirection * Time.deltaTime);
- }
- private void HandleCrouchInput()
- {
- if (Input.GetButtonDown("Fire2"))
- {
- isCrouching = !isCrouching;
- float targetHeight = isCrouching ? crouchingHeight : standingHeight;
- playerCamera.localPosition = new Vector3(0f, targetHeight, 0f);
- }
- if (Input.GetButtonDown("Fire1"))
- {
- isSprinting = true;
- }
- if (Input.GetButtonUp("Fire1"))
- {
- isSprinting = false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement