Files
BABA_YAGA/Assets/Scripts/Player Controller/PlayerJumpState.cs
2026-03-31 08:16:46 +07:00

92 lines
3.5 KiB
C#

using UnityEngine;
namespace OnlyScove.Scripts
{
public class PlayerJumpState : PlayerBaseState
{
private readonly int jumpHash = Animator.StringToHash("Jump");
private readonly int speedHash = Animator.StringToHash("Speed");
private readonly int speedXHash = Animator.StringToHash("Velocity X");
private readonly int speedZHash = Animator.StringToHash("Velocity Z");
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()
{
// Set initial velocity for the Jump Blend Tree (2D Freeform)
Vector2 input = stateMachine.Input.MoveInput;
stateMachine.Anim.SetFloat(speedXHash, input.x);
stateMachine.Anim.SetFloat(speedZHash, input.y);
// Set Speed parameter to help distinguish between Idle Jump (0) and Run Jump (0.7+)
float moveAmount = input.magnitude;
stateMachine.Anim.SetFloat(speedHash, moveAmount > 0.1f ? 1.0f : 0f);
stateMachine.Anim.ResetTrigger(jumpHash);
stateMachine.Anim.SetTrigger(jumpHash);
// Physic formula: v = sqrt(h * -2 * g)
stateMachine.VelocityY = Mathf.Sqrt(stateMachine.JumpHeight * -2f * Physics.gravity.y);
stateMachine.Input.OnSprintEvent += OnAirDash;
}
public override void Tick(float deltaTime)
{
stateMachine.VelocityY += Physics.gravity.y * deltaTime;
Vector2 input = stateMachine.Input.MoveInput;
Vector3 inputDir = new Vector3(input.x, 0, input.y).normalized;
Vector3 moveDirection = stateMachine.Cam != null ? stateMachine.Cam.PlanarRotation * inputDir : inputDir;
Vector3 velocity = moveDirection * jumpSpeed;
velocity.y = stateMachine.VelocityY;
stateMachine.Controller.Move(velocity * deltaTime);
// Cập nhật Animator cho việc di chuyển trên không (Blend Tree sẽ tự mượt mà theo các giá trị này)
float multiplier = stateMachine.Input.IsSprintHeld ? 1f : 0.5f;
stateMachine.Anim.SetFloat(speedXHash, input.x * multiplier, stateMachine.AnimationDamping, deltaTime);
stateMachine.Anim.SetFloat(speedZHash, input.y * multiplier, stateMachine.AnimationDamping, deltaTime);
if (moveDirection != Vector3.zero)
{
Quaternion targetRot = Quaternion.LookRotation(moveDirection);
stateMachine.transform.rotation = Quaternion.RotateTowards(
stateMachine.transform.rotation,
targetRot,
stateMachine.RotationSpeed * deltaTime
);
}
if (stateMachine.VelocityY <= 0f)
{
stateMachine.SwitchState(new PlayerFallState(stateMachine, jumpSpeed));
}
}
private void OnAirDash()
{
stateMachine.SwitchState(new PlayerAirDashState(stateMachine));
}
public override void PhysicsTick(float fixedDeltaTime) {}
public override void Exit()
{
stateMachine.Input.OnSprintEvent -= OnAirDash;
}
}
}