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
、それは本当に混乱しています