Action/Actions/PlatformerJump.cs

86 lines
2.6 KiB
C#
Raw Normal View History

2022-11-20 18:31:16 +03:00
using Syntriax.Modules.ToggleState;
using Syntriax.Modules.Trigger;
using UnityEngine;
namespace Syntriax.Modules.Action
{
2022-11-20 18:45:36 +03:00
2022-11-20 18:31:16 +03:00
[RequireComponent(typeof(Rigidbody2D))]
2022-11-20 18:45:36 +03:00
public class PlatformerJump : ActionBaseWithDeactivation
2022-11-20 18:31:16 +03:00
{
2022-11-20 18:45:36 +03:00
[SerializeField] private float jumpSpeed = 10f;
2022-11-20 18:31:16 +03:00
public float JumpSpeed { get => jumpSpeed; set => jumpSpeed = value; }
2022-11-20 18:45:36 +03:00
[SerializeField] private float fallThreshold = 0f;
public float FallThreshold { get => fallThreshold; set => fallThreshold = value; }
2022-11-20 18:31:16 +03:00
[SerializeField] private float fallMultiplier = 1.5f;
public float FallMultiplier
{
get => fallMultiplier;
set => fallMultiplier = value * Time.fixedDeltaTime;
}
2022-11-20 18:45:36 +03:00
2022-11-20 18:31:16 +03:00
[SerializeField] private float suspensionMultiplier = 1f;
public float SuspensionMultiplier
{
get => suspensionMultiplier;
set => suspensionMultiplier = value * Time.fixedDeltaTime;
}
2022-11-20 18:45:36 +03:00
protected IToggleState gameObjectToggleState = null;
2022-11-20 18:31:16 +03:00
protected bool airSuspension = false;
protected IGroundTrigger groundCheck = null;
protected Rigidbody2D rigid = null;
protected virtual void Start()
{
rigid = GetComponent<Rigidbody2D>();
groundCheck = GetComponentInChildren<IGroundTrigger>();
gameObjectToggleState = GetComponent<IToggleState>();
2022-11-20 18:45:36 +03:00
FallMultiplier = fallMultiplier;
SuspensionMultiplier = suspensionMultiplier;
2022-11-20 18:31:16 +03:00
}
protected virtual void FixedUpdate()
{
if (!ToggleState.IsToggledNullChecked() || !gameObjectToggleState.IsToggledNullChecked())
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;
}
2022-11-20 18:45:36 +03:00
protected override void OnDeactivated()
2022-11-20 18:31:16 +03:00
{
2022-11-20 18:45:36 +03:00
if (!gameObjectToggleState.IsToggledNullChecked())
return;
airSuspension = false;
}
protected override void OnActivated()
{
if (!gameObjectToggleState.IsToggledNullChecked())
2022-11-20 18:31:16 +03:00
return;
if (groundCheck.IsTrigerred)
Jump();
airSuspension = true;
}
}
}