Files
BABA_YAGA/Assets/Scripts/Player Controller/PlayerJumpState.cs

75 lines
2.4 KiB
C#
Raw Normal View History

2026-03-26 20:27:19 +07:00
using UnityEngine;
namespace OnlyScove.Scripts
{
public class PlayerJumpState : PlayerBaseState
{
private readonly int jumpHash = Animator.StringToHash("Jump");
2026-03-31 08:16:46 +07:00
private readonly int speedHash = Animator.StringToHash("Speed");
private readonly int speedXHash = Animator.StringToHash("Velocity X");
private readonly int speedZHash = Animator.StringToHash("Velocity Z");
2026-03-26 20:27:19 +07:00
private float jumpSpeed;
public PlayerJumpState(PlayerStateMachine stateMachine, float jumpSpeed = -1f) : base(stateMachine)
{
if (jumpSpeed < 0)
{
this.jumpSpeed = stateMachine.WalkSpeed;
}
else
{
this.jumpSpeed = jumpSpeed;
}
}
public override void Enter()
{
2026-04-08 12:38:39 +07:00
// Sử dụng dữ liệu đồng bộ
Vector2 input = stateMachine.MoveInput;
2026-03-31 08:16:46 +07:00
stateMachine.Anim.ResetTrigger(jumpHash);
2026-03-26 20:27:19 +07:00
stateMachine.Anim.SetTrigger(jumpHash);
// Physic formula: v = sqrt(h * -2 * g)
2026-04-08 12:38:39 +07:00
stateMachine.VelocityY = Mathf.Sqrt(stateMachine.JumpHeight * -2f * stateMachine.Gravity);
2026-03-31 08:16:46 +07:00
stateMachine.Input.OnSprintEvent += OnAirDash;
2026-03-26 20:27:19 +07:00
}
public override void Tick(float deltaTime)
{
2026-04-08 12:38:39 +07:00
stateMachine.VelocityY += stateMachine.Gravity * deltaTime;
2026-03-26 20:27:19 +07:00
2026-04-08 12:38:39 +07:00
Vector2 input = stateMachine.MoveInput;
2026-03-26 20:27:19 +07:00
Vector3 inputDir = new Vector3(input.x, 0, input.y).normalized;
2026-04-08 12:38:39 +07:00
Vector3 moveDirection = stateMachine.NetworkedCameraRotation * inputDir;
moveDirection.y = 0;
moveDirection.Normalize();
2026-03-26 20:27:19 +07:00
Vector3 velocity = moveDirection * jumpSpeed;
velocity.y = stateMachine.VelocityY;
2026-04-08 12:38:39 +07:00
// Đồng bộ di chuyển và xoay
stateMachine.Move(velocity, 1.0f, deltaTime);
stateMachine.Rotate(moveDirection, deltaTime);
2026-03-31 08:16:46 +07:00
2026-03-26 20:27:19 +07:00
if (stateMachine.VelocityY <= 0f)
{
stateMachine.SwitchState(new PlayerFallState(stateMachine, jumpSpeed));
}
}
2026-03-31 08:16:46 +07:00
private void OnAirDash()
{
stateMachine.SwitchState(new PlayerAirDashState(stateMachine));
}
2026-03-26 20:27:19 +07:00
public override void PhysicsTick(float fixedDeltaTime) {}
2026-03-31 08:16:46 +07:00
public override void Exit()
{
stateMachine.Input.OnSprintEvent -= OnAirDash;
}
2026-03-26 20:27:19 +07:00
}
}