Movement/SpecialAction/Actions/PlatformerJump.cs

88 lines
2.5 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; protected set; } = null;
public float FallThreshold { get; set; } = 0f;
private float fallMultiplier = 0f;
public float FallMultiplier
{
get => fallMultiplier;
set => fallMultiplier = value * Time.fixedDeltaTime;
}
private float suspensionMultiplier = 0f;
public float SuspensionMultiplier
{
get => suspensionMultiplier;
set => suspensionMultiplier = value * Time.fixedDeltaTime;
}
protected bool airSuspension = false;
protected IGroundTrigger groundCheck = null;
protected Rigidbody2D rigid = null;
protected IToggleState toggleState = null;
protected virtual void Awake()
{
JumpSpeed = 10f;
FallMultiplier = 1.5f;
SuspensionMultiplier = 1f;
EnabledToggleState = new MemberToggleState();
}
protected virtual void Start()
{
rigid = GetComponent<Rigidbody2D>();
groundCheck = GetComponentInChildren<IGroundTrigger>();
toggleState = GetComponent<IToggleState>();
}
protected virtual void FixedUpdate()
{
if (!EnabledToggleState.Toggled)
return;
if (rigid.velocity.y < FallThreshold)
ApplySuspension(SuspensionMultiplier);
else if (!airSuspension)
ApplySuspension(FallMultiplier);
}
protected virtual void ApplySuspension(float multiplier)
=> rigid.velocity += Physics2D.gravity * multiplier;
protected virtual void Jump()
{
Vector2 velocity = rigid.velocity;
velocity.y = JumpSpeed;
rigid.velocity = velocity;
}
public virtual void Activate()
{
if (!toggleState.Toggled)
return;
if (groundCheck.IsTrigerred)
Jump();
airSuspension = true;
}
public virtual void Deactivate()
{
if (!toggleState.Toggled)
return;
airSuspension = false;
}
}
}