1
This commit is contained in:
67
BITKit/Scripts/StateMachine/StateMachineNode.cs
Normal file
67
BITKit/Scripts/StateMachine/StateMachineNode.cs
Normal file
@@ -0,0 +1,67 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
24
BITKit/Scripts/StateMachine/StateNode.cs
Normal file
24
BITKit/Scripts/StateMachine/StateNode.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using Godot;
|
||||
using System;
|
||||
|
||||
namespace BITKit.StateMachine;
|
||||
public partial class StateNode : Node, IState
|
||||
{
|
||||
public virtual bool Enabled { get; set; }
|
||||
public virtual void Initialize()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public virtual void OnStateEntry(IState old)
|
||||
{
|
||||
}
|
||||
|
||||
public virtual void OnStateUpdate(float deltaTime)
|
||||
{
|
||||
}
|
||||
|
||||
public virtual void OnStateExit(IState old, IState newState)
|
||||
{
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user