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
,这真的很令人困惑