[Unity插件]Lua行为树(四):条件节点和行为节点

时间:2022-06-01 19:24:17

条件节点和行为节点,这两种节点本身的设计比较简单,项目中编写行为树节点一般就是扩展这两种节点,而Decorator和Composite节点只需要使用内置的就足够了。

它们的继承关系如下:

Conditional->Task

Action->Task

代码如下:

BTAction.lua

 BTAction = BTTask:New();

 local this = BTAction;

 function this:New()
local o = {};
setmetatable(o, self);
self.__index = self;
return o;
end

BTConditional.lua

 BTConditional = BTTask:New();

 local this = BTConditional;

 function this:New()
local o = {};
setmetatable(o, self);
self.__index = self;
return o;
end

BTLog.lua

 --[[
参考BehaviorDesigner-Action-Log
--]]
BTLog = BTAction:New(); local this = BTLog; function this:New(text)
local o = {};
setmetatable(o, self);
self.__index = self;
o.text = text;
return o;
end function this:OnUpdate()
print(self.text);
return BTTaskStatus.Success;
end

BTIsNullOrEmpty.lua

 --[[
参考BehaviorDesigner-Conditional-IsNullOrEmpty
--]]
BTIsNullOrEmpty = BTConditional:New(); local this = BTIsNullOrEmpty; function this:New(text)
local o = {};
setmetatable(o, self);
self.__index = self;
o.text = text;
return o;
end function this:OnUpdate()
if (not self.text or self.text == "") then
return BTTaskStatus.Success;
else
return BTTaskStatus.Failure;
end
end

TestBehaviorTree.lua

 TestBehaviorTree = BTBehaviorTree:New();

 local this = TestBehaviorTree;

 function this:New()
local o = {};
setmetatable(o, self);
self.__index = self;
this:Init();
return o;
end function this:Init()
local sequence = BTSequence:New();
local isNullOrEmpty = BTIsNullOrEmpty:New("");
local log = BTLog:New("This is a empty string");
sequence:AddChild(isNullOrEmpty);
sequence:AddChild(log);
this:PushTask(sequence);
end

输出如下:

[Unity插件]Lua行为树(四):条件节点和行为节点