74 lines
2.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerJumpScript : MonoBehaviour
{
[SerializeField] private InputActionProperty _JumpButton;
[SerializeField] private float _JumpHeight = 0f; // Высота прыжка
[SerializeField] private CharacterController _CharacterController;
[SerializeField] private LayerMask _GroundLayers;
[SerializeField] private float rad = 0;
private float _verticalVelocity = 0f; // Вертикальная скорость
private float _gravity = Physics.gravity.y; // Гравитация
private bool _isGrounded;
private void Update()
{
_isGrounded = IsGrounded();
//if (_JumpButton.action.WasPressedThisFrame())
//{
// if (_isGrounded)
// {
// Debug.Log("Will Jump from gruond");
// }
// else
// {
// Debug.Log("Not Jump");
// }
//}
// Если персонаж на земле, обнуляем вертикальную скорость и проверяем прыжок
if (_isGrounded)
{
_verticalVelocity = -1f; // Небольшое значение, чтобы персонаж не зависал в воздухе
// Если кнопка прыжка нажата
if (_JumpButton.action.WasPressedThisFrame())
{
Jump();
}
}
else
{
// Применяем гравитацию, если персонаж не на земле
_verticalVelocity += _gravity * Time.deltaTime;
}
// Перемещение персонажа с учетом вертикальной скорости
Vector3 movement = new Vector3(0, _verticalVelocity, 0);
if (_CharacterController.enabled == true)
{
_CharacterController.Move(movement * Time.deltaTime);
}
}
private bool IsGrounded()
{
return Physics.CheckSphere(transform.position, rad, _GroundLayers); // Радиус может быть отрегулирован
}
private void Jump()
{
if (_isGrounded)
{
// Применяем силу прыжка
_verticalVelocity = Mathf.Sqrt(_JumpHeight * -2f * _gravity); // Формула для прыжка с заданной высотой
}
}
}