feat: added basic state machine system & Engine.Systems class library
This commit is contained in:
49
Engine.Systems/StateMachine/StateMachine.cs
Normal file
49
Engine.Systems/StateMachine/StateMachine.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.StateMachine;
|
||||
|
||||
public class StateMachine : Behaviour
|
||||
{
|
||||
public event OnStateChangedEventHandler? OnStateChanged = null;
|
||||
|
||||
private IState _state = new State();
|
||||
public IState State
|
||||
{
|
||||
get => _state;
|
||||
set
|
||||
{
|
||||
if (_state == value)
|
||||
return;
|
||||
|
||||
IState previousState = _state;
|
||||
previousState.OnStateTransitionReady -= OnStateTransitionReady;
|
||||
|
||||
_state = value;
|
||||
previousState.TransitionFrom(value);
|
||||
value.TransitionTo(_state);
|
||||
OnStateChanged?.Invoke(this, previousState, value);
|
||||
|
||||
value.OnStateTransitionReady += OnStateTransitionReady;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnStateTransitionReady(IState sender, IState toState)
|
||||
{
|
||||
State = toState;
|
||||
while (State.GetNextState() is IState nextState)
|
||||
State = nextState;
|
||||
}
|
||||
|
||||
protected override void OnUpdate()
|
||||
{
|
||||
if (State is null)
|
||||
return;
|
||||
|
||||
while (State.GetNextState() is IState nextState)
|
||||
State = nextState;
|
||||
|
||||
State.Update();
|
||||
}
|
||||
|
||||
public delegate void OnStateChangedEventHandler(StateMachine sender, IState previousState, IState newState);
|
||||
}
|
Reference in New Issue
Block a user