68 lines
1.5 KiB
C#
68 lines
1.5 KiB
C#
|
using Godot;
|
||
|
using System;
|
||
|
using System.Collections.Generic;
|
||
|
using System.Linq;
|
||
|
|
||
|
namespace BITKit.StateMachine
|
||
|
{
|
||
|
public abstract partial class StateMachineNode<T> : Node ,IStateMachine<T> where T : class, IState
|
||
|
{
|
||
|
public bool Enabled { get; set; }
|
||
|
public T CurrentState { get; set; }
|
||
|
public event Action<T, T> OnStateChanged;
|
||
|
public IDictionary<Type, T> StateDictionary { get; } = new Dictionary<Type, T>();
|
||
|
public void Initialize()
|
||
|
{
|
||
|
foreach (var x in StateDictionary)
|
||
|
{
|
||
|
x.Value.Initialize();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public void UpdateState(float deltaTime)
|
||
|
{
|
||
|
CurrentState?.OnStateUpdate(deltaTime);
|
||
|
}
|
||
|
|
||
|
public void DisposeState()
|
||
|
{
|
||
|
CurrentState?.OnStateExit(CurrentState,null);
|
||
|
CurrentState = null;
|
||
|
}
|
||
|
|
||
|
public void TransitionState<State>() where State : T
|
||
|
{
|
||
|
TransitionState(StateDictionary[typeof(State)]);
|
||
|
}
|
||
|
|
||
|
public void TransitionState(T state)
|
||
|
{
|
||
|
CurrentState?.OnStateExit(CurrentState, state);
|
||
|
var previousState = CurrentState;
|
||
|
CurrentState = state;
|
||
|
state.OnStateEntry(previousState);
|
||
|
OnStateChanged?.Invoke(previousState, CurrentState);
|
||
|
CurrentState = state;
|
||
|
}
|
||
|
|
||
|
public override void _Ready()
|
||
|
{
|
||
|
base._Ready();
|
||
|
foreach (var x in MathNode.GetAllNode(this).OfType<T>())
|
||
|
{
|
||
|
StateDictionary.Add(x.GetType(), x);
|
||
|
}
|
||
|
|
||
|
Initialize();
|
||
|
if (StateDictionary.Count > 0)
|
||
|
TransitionState(StateDictionary.First().Value);
|
||
|
}
|
||
|
|
||
|
public override void _Process(double delta)
|
||
|
{
|
||
|
base._Process(delta);
|
||
|
CurrentState?.OnStateUpdate((float)delta);
|
||
|
}
|
||
|
}
|
||
|
}
|