2026-02-24 11:02:55 +01:00
|
|
|
using System;
|
2026-02-16 15:02:20 +01:00
|
|
|
using UnityEngine;
|
|
|
|
|
using UnityEngine.InputSystem;
|
|
|
|
|
|
|
|
|
|
public class PlayerMovement : MonoBehaviour
|
|
|
|
|
{
|
2026-02-24 09:33:08 +01:00
|
|
|
private InputMaster _inputMaster;
|
2026-02-16 15:02:20 +01:00
|
|
|
[SerializeField] private CharacterController controller;
|
|
|
|
|
[SerializeField] private float speed;
|
2026-02-24 11:02:55 +01:00
|
|
|
[SerializeField] private Transform groundCheck;
|
|
|
|
|
private float _groundDistance = 0.4f;
|
|
|
|
|
[SerializeField] private LayerMask groundMask;
|
2026-02-24 09:33:08 +01:00
|
|
|
|
2026-02-16 15:02:20 +01:00
|
|
|
private Vector2 _moveDirection;
|
2026-02-24 11:02:55 +01:00
|
|
|
private Vector3 _velocity;
|
|
|
|
|
private readonly float _gravity = -9.81f * 2f;
|
|
|
|
|
private bool _isGrounded;
|
|
|
|
|
|
|
|
|
|
private float _jumpHeight = 3f;
|
2026-02-16 15:02:20 +01:00
|
|
|
|
|
|
|
|
private void Awake()
|
|
|
|
|
{
|
|
|
|
|
controller = GetComponent<CharacterController>();
|
2026-02-24 09:33:08 +01:00
|
|
|
_inputMaster = new InputMaster();
|
|
|
|
|
_inputMaster.Player.Move.Enable();
|
2026-02-24 11:02:55 +01:00
|
|
|
_inputMaster.Player.Jump.Enable();
|
2026-02-24 09:33:08 +01:00
|
|
|
}
|
|
|
|
|
|
2026-02-24 11:02:55 +01:00
|
|
|
private void Update()
|
|
|
|
|
{
|
|
|
|
|
_isGrounded = Physics.CheckSphere(groundCheck.position, _groundDistance, groundMask);
|
|
|
|
|
if (_isGrounded && _velocity.y < 0)
|
|
|
|
|
{
|
|
|
|
|
_velocity.y = -2f; //force player on the ground
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_moveDirection = _inputMaster.Player.Move.ReadValue<Vector2>();
|
|
|
|
|
Vector3 move = transform.right * _moveDirection.x + transform.forward * _moveDirection.y;
|
|
|
|
|
controller.Move(move * (speed * Time.deltaTime));
|
|
|
|
|
|
|
|
|
|
_velocity.y += _gravity * Time.deltaTime;
|
|
|
|
|
controller.Move(_velocity * Time.deltaTime); // multiply again because of m/s^2
|
2026-02-16 15:02:20 +01:00
|
|
|
}
|
|
|
|
|
|
2026-02-24 11:02:55 +01:00
|
|
|
public void Jump(InputAction.CallbackContext context)
|
|
|
|
|
{
|
|
|
|
|
if (context.performed)
|
|
|
|
|
{
|
|
|
|
|
if (_isGrounded)
|
|
|
|
|
{
|
|
|
|
|
_velocity.y = (float)Math.Sqrt(_jumpHeight * -2f * _gravity);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void OnDisable()
|
|
|
|
|
{
|
|
|
|
|
_inputMaster.Player.Move.Disable();
|
|
|
|
|
_inputMaster.Player.Jump.Disable();
|
|
|
|
|
}
|
2026-02-16 15:02:20 +01:00
|
|
|
}
|