Skip to content

Instantly share code, notes, and snippets.

@mzaks
Last active July 24, 2017 09:37
Show Gist options
  • Save mzaks/cc813421aefc53ec6fd4696468cf6dd8 to your computer and use it in GitHub Desktop.
Save mzaks/cc813421aefc53ec6fd4696468cf6dd8 to your computer and use it in GitHub Desktop.
A behaviour tree system for Entitas
public sealed class BTSystem: IExecuteSystem
{
IBehaviorNode rootNode;
public BTSystem(IBehaviorNode rootNode)
{
this.rootNode = rootNode;
}
void Execute()
{
rootNode.Execute();
}
}
enum NodeStatus
{
Success, Failure, Running
}
public interface IBehaviorNode
{
NodeStatus Execute();
}
public sealed class Sequence : IBehaviorNode
{
IBehaviorNode[] nodes;
int startIndex = 0;
public Sequence(params IBehaviorNode[] nodes)
{
this.nodes = nodes;
}
public NodeStatus Execute()
{
var result = NodeStatus.Success;
for (int i = startIndex; i < nodes.Length; i++)
{
result = nodes[i].Execute();
if (result == NodeStatus.Failure) {
break;
}
if (result == NodeStatus.Running) {
startIndex = i;
return result;
}
}
startIndex = 0;
return result;
}
}
public sealed class Selector : IBehaviorNode
{
IBehaviorNode[] nodes;
int startIndex = 0;
public Selector(params IBehaviorNode[] nodes)
{
this.nodes = nodes;
}
public NodeStatus Execute()
{
var result = NodeStatus.Success;
for (int i = startIndex; i < nodes.Length; i++)
{
result = nodes[i].Execute();
if (result == NodeStatus.Success){
break;
}
if (result == NodeStatus.Running) {
startIndex = i;
return result;
}
}
startIndex = 0;
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment