98 lines
3.2 KiB
C#
98 lines
3.2 KiB
C#
using Code.Infrastructure.Configs;
|
|
using Code.Infrastructure.EventBus;
|
|
using Reflex.Attributes;
|
|
using UnityEngine;
|
|
|
|
namespace Code.Example.Platformer.Entity
|
|
{
|
|
public interface IGameplayFreezeable : IGlobalSubscriber
|
|
{
|
|
void Freeze();
|
|
void UnFreeze();
|
|
}
|
|
public abstract class Entity : MonoBehaviour, IGameplayFreezeable
|
|
{
|
|
protected static readonly int VelocityY = Animator.StringToHash("VelocityY");
|
|
protected static readonly int VelocityX = Animator.StringToHash("VelocityX");
|
|
protected static readonly int OnGround = Animator.StringToHash("OnGround");
|
|
protected static readonly int OnHit = Animator.StringToHash("OnHit");
|
|
protected static readonly int OnDeath = Animator.StringToHash("OnDeath");
|
|
protected static readonly int Died = Animator.StringToHash("Died");
|
|
|
|
[SerializeField] protected new Rigidbody2D rigidbody2D;
|
|
[SerializeField] protected Animator animator;
|
|
[SerializeField] protected SpriteRenderer spriteRenderer;
|
|
[SerializeField] private Vector2 groundPoint;
|
|
|
|
private PlatformerEntityData _data; // TODO
|
|
protected bool isFreezed = true;
|
|
protected bool onGround;
|
|
private EventBus _eventBus;
|
|
|
|
private Vector2 _frozenVelocity;
|
|
|
|
public void SetData(PlatformerEntityData data)
|
|
{
|
|
_data = data;
|
|
}
|
|
|
|
[Inject]
|
|
private void Construct(EventBus eventBus)
|
|
{
|
|
_eventBus = eventBus;
|
|
_eventBus.Subscribe(this);
|
|
}
|
|
|
|
protected virtual void OnDestroy()
|
|
{
|
|
_eventBus.Unsubscribe(this);
|
|
}
|
|
|
|
public void Freeze()
|
|
{
|
|
_frozenVelocity = rigidbody2D.linearVelocity;
|
|
rigidbody2D.linearVelocity = Vector2.zero;
|
|
|
|
rigidbody2D.bodyType = RigidbodyType2D.Kinematic;
|
|
isFreezed = true;
|
|
}
|
|
public void UnFreeze()
|
|
{
|
|
rigidbody2D.linearVelocity = _frozenVelocity;
|
|
|
|
rigidbody2D.bodyType = RigidbodyType2D.Dynamic;
|
|
isFreezed = false;
|
|
}
|
|
|
|
|
|
protected virtual void Update()
|
|
{
|
|
if(isFreezed) return;
|
|
|
|
animator.SetFloat(VelocityX, rigidbody2D.linearVelocityX);
|
|
animator.SetFloat(VelocityY, rigidbody2D.linearVelocityY);
|
|
}
|
|
|
|
protected virtual void HandleFlipX() => spriteRenderer.flipX = rigidbody2D.linearVelocity.x < 0.01f;
|
|
|
|
protected virtual void FixedUpdate()
|
|
{
|
|
if(isFreezed) return;
|
|
|
|
onGround = CheckGround();
|
|
animator.SetBool(OnGround, onGround);
|
|
|
|
Move();
|
|
|
|
if(rigidbody2D.linearVelocity.x is > 0.01f or < -0.01f) HandleFlipX();
|
|
}
|
|
|
|
protected virtual bool CheckGround()
|
|
{
|
|
UnityEngine.Debug.DrawLine(transform.position,(Vector2)transform.position + groundPoint, Color.green);
|
|
return Physics2D.OverlapPoint((Vector2)transform.position + groundPoint, LayerMasks.Masks[LayerMaskType.PlatformerGround]);
|
|
}
|
|
|
|
protected abstract void Move();
|
|
}
|
|
} |