using Godot; using System; using System.Collections.Generic; using System.Linq; namespace BITKit.StateMachine { public abstract partial class StateMachineNode : Node ,IStateMachine where T : class, IState { public bool Enabled { get; set; } public T CurrentState { get; set; } public event Action OnStateChanged; public IDictionary StateDictionary { get; } = new Dictionary(); 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() 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()) { 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); } } }