1
我試圖添加一個函數,從表格目標中隨機選擇對象。我在某處讀到你可以使用targets[math.random(#targets)]
,但是當我這樣做時,不管resetTarget()
調用是什麼,它都不會重置其中一個目標,它實際上並不會使下一個目標變爲隨機。如何從Lua中的表格中隨機選擇一個對象?
local targets -- an array of target objects
local bomb = display.newImage("bomb.png")
local asteroid = display.newImage("asteroid.png")
local balloon = display.newImage("balloon.png")
targets = { bomb, asteroid, balloon }
function createTarget()
for i = 1, #targets do
local t = targets[i]
t.x = WIDTH + 50 -- start slightly off screen to the right
t.y = math.random(100, HEIGHT - 100) -- at random altitude
end
end
function resetTarget(obj)
createTarget()
end
function detectHits()
-- Do hit detection for ball against each target
local HIT_SLOP = BIRD_RADIUS * 2 -- Adjust this to adjust game difficulty
for i = 1, #targets do
local t = targets[i]
if math.abs(t.x - bird.x) <= HIT_SLOP
and math.abs(t.y - bird.y) <= HIT_SLOP then
-- Hit
isBomb(t)
isAsteroid(t)
isBalloon(t)
resetTarget(t)
updateScore()
end
end
end
隨機目標的目標,那就是需要調用createTarget(),它應該創建一個隨機目標。 – jeppy7 2014-09-26 19:16:01
此外,只要你的代碼行currentTarget = targers [rand],應該是currentTarget = targets [rand]。另外,我相信編寫lua函數的標準方法如下... function newTarget()... – jeppy7 2014-09-26 19:23:13
更好地使用'#targets'而不是'table.maxn(targets)'。 – lhf 2014-09-26 19:49:16