Lua:从“math.random”生成的值未被使用

Lua: Value generated from `math.random` not being used

Lua 对我来说是一门新语言,但我现在看到的行为完全让我感到困惑。

我有一段代码如下:

function PlayState:update(dt)
    -- update timer for pipe spawning
    self.timer = self.timer + dt

    -- spawn a new pipe pair every second and a half
    if self.timer > 2 then
        -- Some code here
    end

    -- Some more code here
end

如您所见,我每 2 秒 运行 一些代码(生成一个对象)。现在我想使用 math.random 每隔 1 到 4 秒生成一个对象。 .所以我试过这个:

function PlayState:update(dt)
    -- update timer for pipe spawning
    self.timer = self.timer + dt

    timeToCheck = math.random(4)
    print('timeToCheck: ' .. timeToCheck)

    -- spawn a new pipe pair every second and a half
    if self.timer > timeToCheck then
        -- Some code here
    end

    -- Some more code here
end

但这不起作用..当我这样做时,对象之间的距离为零。我添加了 print('timeToCheck: ' .. timeToCheck) 以查看随机数是否正确生成并且确实如此。输出如下:

timeToCheck: 4
timeToCheck: 3
timeToCheck: 1
timeToCheck: 3
timeToCheck: 1
timeToCheck: 4
timeToCheck: 1
timeToCheck: 3
timeToCheck: 1
-- etc..

如果我将 timeToCheck 更改为硬编码的东西(例如:timeToCheck = 3),那么对象将按预期分开。

太疯狂了。我在这里错过了什么?

更新:

我为 self.timer 添加了另一条打印消息。另外,我在下面包含了更多代码,因此您可以看到我在哪里重置了计时器:

function PlayState:update(dt)
    -- update timer for pipe spawning
    self.timer = self.timer + dt

    timeToCheck = math.random(4)
    print('timeToCheck: ' .. timeToCheck)
    print('self.timer: ' .. self.timer)

    -- spawn a new pipe pair every second and a half
    if self.timer > timeToCheck then
        -- modify the last Y coordinate we placed so pipe gaps aren't too far apart
        -- no higher than 10 pixels below the top edge of the screen,
        -- and no lower than a gap length (90 pixels) from the bottom
        local y = math.max(-PIPE_HEIGHT + 10, 
            math.min(self.lastY + math.random(-20, 20), VIRTUAL_HEIGHT - 90 - PIPE_HEIGHT))
        self.lastY = y

        -- add a new pipe pair at the end of the screen at our new Y
        table.insert(self.pipePairs, PipePair(y))

        -- reset timer
        self.timer = 0
    end
    -- more code here (not relevant)
end

如您所见,我将计时器设置为 0 的唯一地方是在 if 语句的末尾。这是 print 的输出:

timeToCheck: 2
self.timer: 1.0332646000024
timeToCheck: 4
self.timer: 1.0492977999966
timeToCheck: 1
self.timer: 1.0663072000025
timeToCheck: 2
self.timer: 0.016395300015574
timeToCheck: 4
self.timer: 0.032956400013063
timeToCheck: 2
self.timer: 0.049966399994446
timeToCheck: 2
self.timer: 0.066371900000377
timeToCheck: 3
self.timer: 0.083729100006167
-- etc...

对不起,如果我在这里很密集,但我完全是 Lua 和游戏编程的菜鸟。请注意,如果我将随机值更改为硬编码值,例如:

timeToCheck = 3,那么就可以正常工作了。它仅在我使用 math.random 时失败,这确实令人困惑

您似乎每帧都设置了一个新的 timeToCheck。这将导致大约每秒产生一次新的 spawn,因为 timeToCheck 几乎可以保证每隔几帧为 1。您只需要在 if 内设置 timeToCheck,同时设置定时器。

-- reset timer
self.timer = 0
timeToCheck = math.random(4)

您可能需要在 update 函数之外的某处初始化 timeToCheck