45 lines
1.1 KiB
C#
Executable File
45 lines
1.1 KiB
C#
Executable File
using System;
|
|
using System.Collections.Generic;
|
|
|
|
namespace UPWG.Core
|
|
{
|
|
public class StateMachine<T>
|
|
where T : Enum
|
|
{
|
|
public T CurrentState { get; private set; }
|
|
public double TimeInState { get; private set; }
|
|
private Dictionary<T, (double, T)> _transitions;
|
|
|
|
public StateMachine(T initial)
|
|
{
|
|
CurrentState = initial;
|
|
TimeInState = 0;
|
|
_transitions = new Dictionary<T, (double, T)>();
|
|
}
|
|
|
|
public void AddTransition(T from, T to, double after = 0)
|
|
{
|
|
_transitions[from] = (after, to);
|
|
}
|
|
|
|
public void SetState(T newState)
|
|
{
|
|
CurrentState = newState;
|
|
TimeInState = 0;
|
|
}
|
|
|
|
public void Update(double elapsed)
|
|
{
|
|
TimeInState += elapsed;
|
|
|
|
if (!_transitions.ContainsKey(CurrentState))
|
|
return;
|
|
|
|
var (maxTime, nextState) = _transitions[CurrentState];
|
|
if (TimeInState > maxTime)
|
|
{
|
|
SetState(nextState);
|
|
}
|
|
}
|
|
}
|
|
} |