Files
OMG/Assets/Scripts/PlayerMovement.cs

67 lines
1.9 KiB
C#
Raw Normal View History

using System;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
private InputMaster _inputMaster;
[SerializeField] private CharacterController controller;
[SerializeField] private float speed;
[SerializeField] private Transform groundCheck;
private float _groundDistance = 0.4f;
[SerializeField] private LayerMask groundMask;
private Vector2 _moveDirection;
private Vector3 _velocity;
private readonly float _gravity = -9.81f * 2f;
private bool _isGrounded;
private float _jumpHeight = 3f;
private void Awake()
{
controller = GetComponent<CharacterController>();
_inputMaster = new InputMaster();
_inputMaster.Player.Move.Enable();
_inputMaster.Player.Jump.Enable();
}
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
}
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();
}
private void OnEnable()
{
_inputMaster.Player.Move.Enable();
_inputMaster.Player.Jump.Enable();
}
}