Last active
July 24, 2017 09:37
-
-
Save mzaks/cc813421aefc53ec6fd4696468cf6dd8 to your computer and use it in GitHub Desktop.
A behaviour tree system for Entitas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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