参考链接:https://blog.csdn.net/u012740992/article/details/79366251
在行为树中,有四种最基本的节点,其继承结构如下:
Action->Task
Conditional->Task
Decorator->ParentTask->Task
Composite->ParentTask->Task
对于整棵树,从上往下,可以对其进行分层,从0开始递增;对于树中的子树,从左到右,可以对其子节点标记索引。
那么,这里的整棵树,对应的就是BehaviorTree,而子树,对应的就是ParentTask。同时,为了方便节点之间的访问,可以引入root和parent,表示该节点的根节点和父节点。
然后我们可以通过BehaviorManager去管理所有的树。
整体结构如下:
代码如下:
Task.lua
BTree.Task = {}; local this = BTree.Task; function this:New(o)
o = o or {};
setmetatable(o, self);
self.__index = self;
return o;
end
ParentTask.lua
BTree.ParentTask = BTree.Task:New(); local this = BTree.ParentTask; function this:New(o)
o = o or {};
o.curChilIndex = ;--当前运行到第几个子节点
o.childTasks = {};--子节点列表
setmetatable(o, self);
self.__index = self;
return o;
end function this:AddChild(task)
local index = #self.childTasks + ;
task.index = index;
task.layer = self.layer + ;
task.parent = self;
task.root = self.root;
end
BehaviorTree.lua
--[[
树的根节点
--]]
BTree.BehaviorTree = {
layer = ,
}; local this = BTree.BehaviorTree; function this:New(o)
o = o or {};
setmetatable(o, self);
self.__index = self;
return o;
end function this:PushTask(task)
task.root = self;
task.parent = self;
task.layer = self.layer + ;
self.startTask = task;
end function this:OnUpdate()
if (self.startTask) then
return self.startTask:OnUpdate();
end
end
BehaviorManager.lua
BTree.BehaviorManager = {}; local this = BTree.BehaviorManager; function this.RunTree(tree)
this.bTree = tree;
this.OnUpdate();
end function this.OnUpdate()
local status = this.bTree:OnUpdate();
while (status == BTree.TaskStatus.Running) do
status = this.bTree:OnUpdate();
end
end
这里可以使用一棵简单的行为树来进行测试:
Log.lua
--[[
参考BehaviorDesigner-Action-Log
--]]
BTree.Log = BTree.Action:New(); local this = BTree.Log; function this:New(text)
local o = {};
setmetatable(o, self);
self.__index = self;
self.text = text;
return o;
end function this:OnUpdate()
print(self.text);
return BTree.TaskStatus.Success;
end
TestBehaviorTree.lua
TestBehaviorTree = BTree.BehaviorTree:New(); local this = TestBehaviorTree; function this:New(o)
o = o or {};
setmetatable(o, self);
self.__index = self;
this:Init();
return o;
end function this:Init()
local log = BTree.Log:New("hello world!");
this:PushTask(log);
end
TestMain.lua
require "BehaviorTree/Core/Init"
require "BehaviorTree/Test/TestBehaviorTree" local tree = TestBehaviorTree:New();
BTree.BehaviorManager.RunTree(tree);
运行环境:Sublime Text 3,使用while循环来代替每帧执行,按F7进行编译,结果如下: