Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.InputSystem;
- [RequireComponent(typeof(CharacterController))]
- public class PlayerController : MonoBehaviour
- {
- [Header("References")]
- public Transform playerCamera;
- [Header("Movement Settings")]
- public float walkSpeed = 5f;
- public float sprintSpeed = 8f;
- public float jumpHeight = 1.5f;
- [Header("Look Settings")]
- public float mouseSensitivity = 0.15f;
- // Component and Input References
- private CharacterController controller;
- private PlayerInputActions inputActions;
- // Internal State
- private Vector3 velocity;
- private float cameraPitch = 0f;
- private void Awake()
- {
- controller = GetComponent<CharacterController>();
- inputActions = new PlayerInputActions();
- // Subscribe to discrete actions (Jump)
- inputActions.Player.Jump.performed += OnJump;
- }
- private void OnEnable()
- {
- inputActions.Enable();
- Cursor.lockState = CursorLockMode.Locked;
- Cursor.visible = false;
- }
- private void OnDisable()
- {
- inputActions.Disable();
- }
- private void OnDestroy()
- {
- // Prevent memory leaks by unsubscribing
- if (inputActions != null)
- {
- inputActions.Player.Jump.performed -= OnJump;
- inputActions.Dispose();
- }
- }
- private void Update()
- {
- HandleLook();
- HandleMovement();
- ApplyGravity();
- }
- private void HandleLook()
- {
- if (playerCamera == null)
- {
- Debug.LogError("[PlayerController] Player Camera is not assigned!");
- return;
- }
- // Poll delta directly rather than caching via events
- Vector2 lookInput = inputActions.Player.Look.ReadValue<Vector2>();
- cameraPitch -= lookInput.y * mouseSensitivity;
- cameraPitch = Mathf.Clamp(cameraPitch, -90f, 90f);
- playerCamera.localRotation = Quaternion.Euler(cameraPitch, 0f, 0f);
- transform.Rotate(Vector3.up * (lookInput.x * mouseSensitivity));
- }
- private void HandleMovement()
- {
- // Poll continuous movement input
- Vector2 moveInput = inputActions.Player.Move.ReadValue<Vector2>();
- // Normalize to prevent faster diagonal movement
- Vector3 moveDirection = (transform.right * moveInput.x + transform.forward * moveInput.y).normalized;
- bool isSprinting = inputActions.Player.Sprint.IsPressed();
- float currentSpeed = isSprinting ? sprintSpeed : walkSpeed;
- controller.Move(moveDirection * (currentSpeed * Time.deltaTime));
- }
- private void ApplyGravity()
- {
- // Reset gravity accumulation when grounded
- if (controller.isGrounded && velocity.y < 0f)
- {
- velocity.y = -2f; // Slight downward force to snap to ground
- }
- velocity.y += Physics.gravity.y * Time.deltaTime;
- controller.Move(velocity * Time.deltaTime);
- }
- private void OnJump(InputAction.CallbackContext context)
- {
- if (controller.isGrounded)
- {
- // Physics formula for jumping: v = sqrt(height * -2 * gravity)
- velocity.y = Mathf.Sqrt(jumpHeight * -2f * Physics.gravity.y);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment