sách gpt4 ai đã đi

coroutine - Thay thế cho coroutine

In lại 作者:行者123 更新时间:2023-12-03 17:07:02 25 4
mua khóa gpt4 Nike

此示例已在另一个问题中用于说明如何使用协程来编写视频游戏中的过场动画:

bob.walkto(jane)
bob.lookat(jane)
bob.say("How are you?")
wait(2)
jane.say("Fine")
...

在恢复协程之前,每个函数都交给执行动画、计时等的主引擎。协程的一种可能替代方案是事件队列而不是代码,但是必须将控制逻辑和循环实现为事件。是否有其他可用于实现此类功能的协程替代方案?我在一些文章中看到了回调,但我不确定代码的外观。

1 Câu trả lời

你没有提到你使用的是什么语言,所以我将用 Lua 编写这个,中间类提供面向对象 - https://github.com/kikito/middleclass (免责声明:我是中间类的创造者)

另一种选择是将过场动画拆分为“ Action 列表”。如果您已经有一个在对象列表上调用“更新”方法的游戏循环,这可能会与您的代码更好地融合。

Giống như thế này:

helloJane = CutScene:new(
WalkAction:new(bob, jane),
LookAction:new(bob, jane),
SayAction:new(bob, "How are you?"),
WaitAction:new(2),
SayAction:new(jane, "Fine")
)

Action 会有 status具有三个可能值的属性: 'new' , 'running' , 'finished' .所有的“ Action 类”都是 Action 的子类,这将定义 bắt đầudừng lại方法,以及将状态初始化为 'new'默认情况下。还有一个默认值 cập nhật抛出错误的方法
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')
kết thúc

Action 的子类可以改进这些方法,并实现 cập nhật .例如,这里是 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
kết thúc

function WaitAction:update(dt)
if os.getTime() - self.startTime >= 2 then
self:stop() -- use the superclass implementation of stop
kết thúc
kết thúc

唯一缺少的实现部分是 CutScene。 CutScene 将主要包含三件事:
* 要执行的操作列表
* 对当前 Action 的引用,或该 Action 在 Action 列表中的索引
* 更新方法如下:
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
kết thúc
kết thúc
kết thúc

有了这个结构,你唯一需要的是你的游戏循环调用 helloJane:update(dt)在每次循环迭代中。并且您消除了对协程的需求。

关于coroutine - 协程的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5324487/

25 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com