Lua 语法下的 knife.timer - 行为不符预期

如果你熟悉 Lua 中的 knife.timer,请查看我的代码并告诉我我有哪些地方错了吧。

我希望做到以下两点:

  1. 拥有一个每秒倒计时的倒计时器,以及
  2. 在六秒后开始闪烁我的角色三秒钟,然后改变他们的状态。

使用下面的代码,我的倒计时器从 9 开始,但一直到负数十几。我的角色在经过约 4 秒后开始闪烁,改变状态后还会继续闪烁几秒钟。

我在主函数中使用了 Timer:update(dt),所以不确定时间是否有误。而且我认为完成时并不会在角色的 16 次闪烁完成之前调用 change state 函数。

function PlayerPilotState:update(dt)
    self.player.currentAnimation:update(dt)
    Timer.every(1, function()
        self.timer = self.timer - 1
    end)

    Timer.after(6, function()
        Timer.every(0.2, function()
            self.player.blinking = not self.player.blinking
            self.player.otherPlayer.blinking = not self.player.otherPlayer.blinking
        end):finish(function()
            self.player:changeState('falling')
            self.player.otherPlayer:changeState('falling')
        end):limit(16)
    end)
end

谢谢!

点赞
用户14098247
用户14098247
  1. 在基础倒计时器中,你从未指定它何时停止。尝试使用:limit(9)或者self.timer = math.max(0,self.timer - 1)

  2. 你是否正确计时了(感受时间流逝很困难),因为你使用了Timer.afterfinish()函数在after()every()后发生,这可能会导致奇怪的事情发生。建议在finish()之前添加limit

Timer.after(6, function()
        Timer.every(0.2, function()
            self.player.blinking = not self.player.blinking
            self.player.otherPlayer.blinking = not self.player.otherPlayer.blinking
        end):limit(16):finish(function()
            self.player:changeState('falling')
            self.player.otherPlayer:changeState('falling')
        end)
    end)
2020-08-25 14:01:08
用户13850885
用户13850885

上述两个评论都非常有用。原来在更新下放置定时器是个坏主意,因为它们要么调用新的定时器,要么刷新得奇怪。我最终得到的并且完美工作的代码是:

function PlayerPilotState:enter(params)
    Timer.every(1, function()
        self.timer = self.timer - 1
    end)

    Timer.after(6, function()
        Timer.every(0.2, function()
            self.player.blinking = not self.player.blinking
            self.player.otherPlayer.blinking = not self.player.otherPlayer.blinking
        end)
        :limit(15)
        :finish(function()
            self.player.blinking = false
            self.player.otherPlayer.blinking = false
            self.player:changeState('falling')
            self.player.otherPlayer:changeState('falling')
        end)
    end)

end

接下来的一个问题是,如何在不使用“进入”函数的情况下执行此操作?我猜任何只调用一次的函数调用(也许带一个布尔标志来调用它)都可以。谢谢!

2020-08-25 22:06:14