1

I'm trying to add a function that randomly selects objects from the table targets. I read somewhere that you can use targets[math.random(#targets)], but when I do that, it doesn't just reset one of the targets regardless of resetTarget() call, and it doesn't actually make the next target random.

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 Answer 1

5

This will work but you will need a forward reference to currentTarget.

What is your function to target the random target?

local newTarget = function()
    local rand = math.random(1,#targets)
    currentTarget = target[rand]
    doSomething()
end
5
  • The random target is targeted upon detectHits(), which in turn calls resetTarget(t) and that is needs to call createTarget(), which should create a random target.
    – jeppy7
    Commented Sep 26, 2014 at 19:16
  • Also, just fyi your line of code currentTarget = targers[rand], should be currentTarget = targets[rand]. Also, I believe the standard way of writing a lua function is as follows... function newTarget()...
    – jeppy7
    Commented Sep 26, 2014 at 19:23
  • 1
    Better use #targets instead of table.maxn(targets).
    – lhf
    Commented Sep 26, 2014 at 19:49
  • # stops at the first nil value, table.maxn does not.
    – Jeremy
    Commented Sep 26, 2014 at 20:49
  • @Jeremy Though table.maxn works in Lua 5.1(which is the version Corona uses now), but it's removed in Lua 5.2
    – Yu Hao
    Commented Sep 27, 2014 at 2:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.