Movement/SpecialAction/Actions/PlatformerJump.cs

88 lines
2.5 KiB
C#
Raw Normal View History

using Syntriax.Modules.Movement.ColliderTrigger;
using Syntriax.Modules.Movement.State;
2021-12-23 12:41:01 +03:00
using UnityEngine;
namespace Syntriax.Modules.Movement.SpecialAction
{
[RequireComponent(typeof(Rigidbody2D))]
public class PlatformerJump : MonoBehaviour, ISpecialActionActivate, ISpecialActionDeactivate
2021-12-23 12:41:01 +03:00
{
public float JumpSpeed { get; set; } = 0f;
public IToggleState EnabledToggleState { get; protected set; } = null;
2021-12-23 12:41:01 +03:00
public float FallThreshold { get; set; } = 0f;
2021-12-23 12:41:01 +03:00
private float fallMultiplier = 0f;
public float FallMultiplier
{
get => fallMultiplier;
set => fallMultiplier = value * Time.fixedDeltaTime;
}
2021-12-23 12:41:01 +03:00
private float suspensionMultiplier = 0f;
public float SuspensionMultiplier
{
get => suspensionMultiplier;
set => suspensionMultiplier = value * Time.fixedDeltaTime;
}
2021-12-23 12:41:01 +03:00
protected bool airSuspension = false;
protected IGroundTrigger groundCheck = null;
protected Rigidbody2D rigid = null;
protected IToggleState toggleState = null;
2021-12-23 12:41:01 +03:00
protected virtual void Awake()
2021-12-23 12:41:01 +03:00
{
JumpSpeed = 10f;
FallMultiplier = 1.5f;
SuspensionMultiplier = 1f;
EnabledToggleState = new MemberToggleState();
2021-12-23 12:41:01 +03:00
}
protected virtual void Start()
2021-12-23 12:41:01 +03:00
{
rigid = GetComponent<Rigidbody2D>();
groundCheck = GetComponentInChildren<IGroundTrigger>();
toggleState = GetComponent<IToggleState>();
2021-12-23 12:41:01 +03:00
}
protected virtual void FixedUpdate()
2021-12-23 12:41:01 +03:00
{
if (!EnabledToggleState.Toggled)
2021-12-23 12:41:01 +03:00
return;
if (rigid.velocity.y < FallThreshold)
ApplySuspension(SuspensionMultiplier);
2021-12-23 12:41:01 +03:00
else if (!airSuspension)
ApplySuspension(FallMultiplier);
2021-12-23 12:41:01 +03:00
}
protected virtual void ApplySuspension(float multiplier)
=> rigid.velocity += Physics2D.gravity * multiplier;
2021-12-23 12:41:01 +03:00
protected virtual void Jump()
2021-12-23 12:41:01 +03:00
{
Vector2 velocity = rigid.velocity;
velocity.y = JumpSpeed;
rigid.velocity = velocity;
}
public virtual void Activate()
2021-12-23 12:41:01 +03:00
{
if (!toggleState.Toggled)
return;
if (groundCheck.IsTrigerred)
2021-12-23 12:41:01 +03:00
Jump();
airSuspension = true;
}
public virtual void Deactivate()
2021-12-23 12:41:01 +03:00
{
if (!toggleState.Toggled)
return;
2021-12-23 12:41:01 +03:00
airSuspension = false;
}
}
}