你没有提到你正在使用哪种语言,所以我将要在Lua与中产阶级提供面向对象的写这篇 - https://github.com/kikito/middleclass(免责声明:我是中产阶级的创造者)
另一种选择会将你的过场动画分成“动作列表”。如果你已经有一个游戏循环在对象列表上调用'update'方法,这可能会更好地融合你的代码。
像这样:
helloJane = CutScene:new(
WalkAction:new(bob, jane),
LookAction:new(bob, jane),
SayAction:new(bob, "How are you?"),
WaitAction:new(2),
SayAction:new(jane, "Fine")
)
行动将有status
属性有三个可能的值:'new'
,'running'
,'finished'
。所有的“动作类别”将是Action
的子类,它们将定义start
和stop
方法,并且默认情况下将状态初始化为'new'
。这里也将是一个默认的update
方法引发错误
行动
Action = class('Action')
function Action:initialize() self.status = 'new' end
function Action:stop() self.status = 'finished' end
function Action:start() self.status = 'running' end
function Action:update(dt)
error('You must re-define update on the subclasses of Action')
end
子类可以提高在这些方法,并实现update
。例如,这里的WaitAction
:
WaitAction = class('WaitAction', Action) -- subclass of Action
function WaitAction:start()
Action.start(self) -- invoke the superclass implementation of start
self.startTime = os.getTime() -- or whatever you use to get the time
end
function WaitAction:update(dt)
if os.getTime() - self.startTime >= 2 then
self:stop() -- use the superclass implementation of stop
end
end
唯一缺少的实现部分是过场动画。过场动画将主要有三个方面: *动作列表执行 * A参考当前动作,或动作列表 对行动的指数*如下所示的更新方法:
function CutScene:update(dt)
local currentAction = self:getCurrentAction()
if currentAction then
currentAction:update(dt)
if currentAction.status == 'finished' then
self:moveToNextAction()
-- more refinements can be added here, for example detecting the end of actions
end
end
end
有了这个结构,你唯一需要的就是你的游戏循环在每次循环迭代时调用helloJane:update(dt)
。而且你消除了对协程的需求。
协程,FSM和基于事件的编程的替代方法是CSP(通信顺序进程)。查看LuaCSP实现(在协程上): https://github.com/loyso/LuaCSP注意:人们通常缺少的是协调和沟通方面。 – 2013-03-12 10:10:01