Movement/SpecialAction/Actions/PlatformerJump.cs

70 lines
1.8 KiB
C#

using Syntriax.Modules.Movement.ColliderCheck;
using UnityEngine;
namespace Syntriax.Modules.Movement.SpecialAction
{
[RequireComponent(typeof(Rigidbody2D))]
public class PlatformerJump : MonoBehaviour, ISpecialActionActivate, ISpecialActionDeactivate, IState
{
public float JumpSpeed { get; set; } = 0f;
public bool StateEnabled { get; set; } = true;
private bool airSuspension = false;
private float fallMultiplier = 0f;
private float suspensionMultiplier = 0f;
private IGroundCheck groundCheck = null;
private Rigidbody2D rigid = null;
private void Awake()
{
JumpSpeed = 10f;
fallMultiplier = 1.5f * Time.fixedDeltaTime;
suspensionMultiplier = 1f * Time.fixedDeltaTime;
}
private void Start()
{
rigid = GetComponent<Rigidbody2D>();
groundCheck = GetComponentInChildren<IGroundCheck>();
}
private void FixedUpdate()
{
if (!StateEnabled)
return;
if (rigid.velocity.y < 0f)
ApplySuspension(suspensionMultiplier);
else if (!airSuspension)
ApplySuspension(fallMultiplier);
}
private void ApplySuspension(float multiplier)
{
rigid.velocity += Physics2D.gravity * multiplier;
}
private void Jump()
{
Vector2 velocity = rigid.velocity;
velocity.y = JumpSpeed;
rigid.velocity = velocity;
}
public void OnActivation()
{
if (groundCheck.IsCollided())
Jump();
airSuspension = true;
}
public void OnDeactivation()
{
airSuspension = false;
}
}
}