Skip to content

Instantly share code, notes, and snippets.

@hclarke

hclarke/BehaviourTrees.cs

Last active Mar 11, 2017
Embed
What would you like to do?
protected delegate State State(bool? prev);
protected readonly State PASS = x => PASS;
protected readonly State FAIL = x => FAIL;
protected readonly State TICK = x => TICK;
Stack<State> stateStack = new Stack<State>();
protected abstract State GetBaseState(); //put your behaviour here
protected void Update() {
bool? prev = null;
if(stateStack.Count == 0) stateStack.Push(GetBaseState());
while(stateStack.count > 0) {
var top = stateStack.Pop();
var res = top(prev);
if(res == PASS) {
prev = true;
continue;
}
if(res == FAIL) {
prev = false;
continue;
}
stateStack.Push(top);
if(res == TICK) {
break;
}
else {
stateStack.Push(res);
prev = null;
continue;
}
}
}
protected State Sequence(params State[] states) {
int i = 0;
State self = null;
return self = prev => {
if(i >= states.Length) return PASS;
if(prev == false) return FAIL;
return states[i++];
};
}
protected State Selector(params State[] states) {
int i = 0;
State self = null;
return self = prev => {
if(i >= states.Length) return FAIL;
if(prev == true) return PASS;
return states[i++];
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment