如何从Lua中的表中随机选择一个对象?

时间:2014-09-26 18:46:39

标签: random lua corona lua-table

我试图添加一个从表目标中随机选择对象的函数。我在某处读到了你可以使用targets[math.random(#targets)],但是当我这样做时,它不会重置其中一个目标而不管resetTarget()调用,并且它实际上并没有下一个目标随机。

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

1 个答案:

答案 0 :(得分:5)

这将有效,但您需要对currentTarget的前向引用。

你定位随机目标的功能是什么?

local newTarget = function()
    local rand = math.random(1,#targets)
    currentTarget = target[rand]
    doSomething()
end