67 lines
2.0 KiB
C#
67 lines
2.0 KiB
C#
namespace AI.BehaviourTree
|
|
{
|
|
public class Sequence : Composite
|
|
{
|
|
Node _currentChild;
|
|
int _currentChildIndex = 0;
|
|
|
|
public Sequence(params Node[] children) : base(children)
|
|
{
|
|
}
|
|
|
|
public override NodeStatus Start()
|
|
{
|
|
if (children.Count == 0) return NodeStatus.Failure;
|
|
|
|
_currentChildIndex = 0;
|
|
_currentChild = children[_currentChildIndex];
|
|
// if status == NodeStatus.Failure => whole sequence fails => return NodeStatus.Failure;
|
|
// if status == NodeStatus.Success => run the next child
|
|
|
|
do
|
|
{
|
|
NodeStatus status = _currentChild?.Start() ?? NodeStatus.Failure;
|
|
if (status == NodeStatus.Failure) return NodeStatus.Failure;
|
|
if (status == NodeStatus.Running) return NodeStatus.Running;
|
|
} while (RunNextChild());
|
|
|
|
return NodeStatus.Success;
|
|
}
|
|
|
|
public override NodeStatus Execute()
|
|
{
|
|
NodeStatus status = _currentChild?.Execute() ?? NodeStatus.Failure;
|
|
|
|
if (status == NodeStatus.Failure) return NodeStatus.Failure;
|
|
if (status == NodeStatus.Running) return NodeStatus.Running;
|
|
|
|
while (RunNextChild())
|
|
{
|
|
status = _currentChild?.Start() ?? NodeStatus.Failure;
|
|
if (status == NodeStatus.Failure) return NodeStatus.Failure;
|
|
if (status == NodeStatus.Running) return NodeStatus.Running;
|
|
}
|
|
|
|
return NodeStatus.Success;
|
|
}
|
|
|
|
public override void Stop()
|
|
{
|
|
_currentChild?.Stop();
|
|
}
|
|
|
|
private bool RunNextChild()
|
|
{
|
|
_currentChild?.Stop();
|
|
_currentChild = null;
|
|
_currentChildIndex++;
|
|
if (_currentChildIndex < children.Count)
|
|
{
|
|
_currentChild = children[_currentChildIndex];
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|
|
} |