如何在Lua中随机选择一个数据表中的对象?

我正在尝试添加一个函数,从目标表中随机选择对象。我在某个地方读到可以使用target [math.random(#targets)],但是当我这样做时,无论调用resetTarget()如何,它都不会重置其中一个目标,并且它实际上也不会使下一个目标随机。

local targets    -- 一个目标对象的数组

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   -- 稍微偏离右侧的屏幕开始
        t.y = math.random(100, HEIGHT - 100)   --在随机高度
    end
end

function resetTarget(obj)
    createTarget()
end

function detectHits()
        -- 每个目标针对球的命中检测
    local HIT_SLOP = BIRD_RADIUS * 2  -- 调整此值以调整游戏难度
    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
            -- 命中
            isBomb(t)
            isAsteroid(t)
            isBalloon(t)
            resetTarget(t)
            updateScore()
        end
    end
end
点赞
用户3839089
用户3839089

这可以工作,但你需要一个关于当前目标的前向引用。

你的函数是用来定位随机目标的?

local newTarget = function()
    local rand = math.random(1,#targets)
    currentTarget = target[rand]
    doSomething()
end
2014-09-26 19:00:25