Movement/SpecialAction/Actions/PlatformerJump.cs

80 lines
2.1 KiB
C#

using Syntriax.Modules.Movement.ColliderTrigger;
using Syntriax.Modules.Movement.State;
using UnityEngine;
namespace Syntriax.Modules.Movement.SpecialAction
{
[RequireComponent(typeof(Rigidbody2D))]
public class PlatformerJump : MonoBehaviour, ISpecialActionActivate, ISpecialActionDeactivate
{
public float JumpSpeed { get; set; } = 0f;
public IToggleState EnabledToggleState { get; private set; } = null;
private bool airSuspension = false;
private float fallMultiplier = 0f;
private float suspensionMultiplier = 0f;
private IGroundTrigger groundCheck = null;
private Rigidbody2D rigid = null;
private IToggleState toggleState = null;
private void Awake()
{
JumpSpeed = 10f;
fallMultiplier = 1.5f * Time.fixedDeltaTime;
suspensionMultiplier = 1f * Time.fixedDeltaTime;
EnabledToggleState = new MemberToggleState();
}
private void Start()
{
rigid = GetComponent<Rigidbody2D>();
groundCheck = GetComponentInChildren<IGroundTrigger>();
toggleState = GetComponent<IToggleState>();
}
private void FixedUpdate()
{
if (!EnabledToggleState.Toggled)
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 Activate()
{
if (!toggleState.Toggled)
return;
if (groundCheck.IsTrigerred)
Jump();
airSuspension = true;
}
public void Deactivate()
{
if (!toggleState.Toggled)
return;
airSuspension = false;
}
}
}