-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStateMachine.cs
More file actions
109 lines (81 loc) · 2.63 KB
/
StateMachine.cs
File metadata and controls
109 lines (81 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using Coroutines;
namespace HatsPlusPlus;
class Coroutine
{
public Func<IEnumerator> func;
public CoroutineHandle handle;
public Coroutine(Func<IEnumerator> func, CoroutineHandle handle)
{
this.func = func;
this.handle = handle;
}
}
/// <summary>
/// Based on Celeste's state machine (thank you very much :>)
/// </summary>
///
internal class StateMachine<T>
{
private T _state;
private bool _updateTwiceUponStateChange;
private Dictionary<T, Action> _begins;
private Dictionary<T, Action> _ends;
private Dictionary<T, Coroutine> _coroutines;
private Dictionary<T, Func<T>> _updates;
private CoroutineRunner _coroutineRunner;
public T PreviousState { get; private set; }
public T State => _state;
public StateMachine(bool updateTwiceUponStateChange = false)
{
_updateTwiceUponStateChange = updateTwiceUponStateChange;
_begins = new();
_ends = new();
_updates = new();
_coroutines = new();
_coroutineRunner = new();
}
public void SetCallBacks(T state, Func<T> onUpdate, Action begin = null, Action end = null, Func<IEnumerator> coroutine = null)
{
_begins[state] = begin;
_ends[state] = end;
_updates[state] = onUpdate;
_coroutines[state] = new Coroutine(coroutine, default(CoroutineHandle));
}
public void ForceState(T newState)
{
if (EqualityComparer<T>.Default.Equals(_state, newState))
return;
_state = newState;
_ends[PreviousState]?.Invoke();
_begins[_state]?.Invoke();
if (_coroutines[PreviousState].func != null)
_coroutineRunner.Stop(_coroutines[PreviousState].handle);
if (_coroutines[newState].func != null)
_coroutines[newState].handle = _coroutineRunner.Run(_coroutines[newState].func.Invoke());
}
public void RunCoroutine(Func<IEnumerator> coroutne)
{
_coroutineRunner.Run(coroutne.Invoke());
}
public void Update(float deltaTime)
{
if (_coroutines[_state] != null)
_coroutineRunner.Update(deltaTime);
if (_updates[_state] != null)
ForceState(_updates[_state].Invoke());
if (!_updateTwiceUponStateChange)
return;
if (!EqualityComparer<T>.Default.Equals(PreviousState, _state))
{
_coroutineRunner.Update(deltaTime);
ForceState(_updates[_state].Invoke());
}
PreviousState = _state;
}
}