在上一篇的基础上,可以测试下行为树的嵌套,所谓的行为树嵌套,就是在一棵行为树下的某一个分支,接入另一棵行为树。
以下面这棵行为树为例:
TestBehaviorTree2.lua
1 TestBehaviorTree2 = BTBehaviorTree:New(); 2 3 local this = TestBehaviorTree2; 4 this.name = "TestBehaviorTree2"; 5 6 function this:New() 7 local o = {}; 8 setmetatable(o, self); 9 self.__index = self; 10 self:Init(); 11 return o; 12 end 13 14 function this:Init() 15 local repeater = BTRepeater:New(2); 16 local sequence = BTSequence:New(); 17 local log = BTLog:New("This is a other tree!!!"); 18 local log2 = BTLog:New("This is a other tree 2!!!"); 19 20 self:SetStartTask(repeater); 21 22 repeater:AddChild(sequence); 23 24 sequence:AddChild(log); 25 sequence:AddChild(log2); 26 end
TestBehaviorTree.lua
1 TestBehaviorTree = BTBehaviorTree:New(); 2 3 local this = TestBehaviorTree; 4 this.name = "TestBehaviorTree"; 5 6 function this:New() 7 local o = {}; 8 setmetatable(o, self); 9 self.__index = self; 10 self:Init(); 11 return o; 12 end 13 14 function this:Init() 15 local repeater = BTRepeater:New(2); 16 local selector = BTSelector:New(); 17 local sequence = BTSequence:New(); 18 local isNullOrEmpty = BTIsNullOrEmpty:New("123"); 19 local log = BTLog:New("This is a empty string!!!"); 20 local tree2 = TestBehaviorTree2:New(); 21 22 self:SetStartTask(repeater); 23 24 repeater:AddChild(selector); 25 26 selector:AddChild(sequence); 27 selector:AddChild(tree2); 28 29 sequence:AddChild(isNullOrEmpty); 30 sequence:AddChild(log); 31 end
打印如下:
扫描二维码关注公众号,回复:
3101858 查看本文章
上面的执行结果是没有问题的,由此可见,将BTBehaviorTree当作节点,然后嵌套在行为树中是可行的。不过通过上面的打印,可以发现嵌套树先被打印,然后总树才被打印,而且嵌套树的层级也是不对的,这是节点添加顺序造成的问题,因此不应该在设置节点或者添加节点时进行打印,应该在整棵数构成完成后进行打印。