Corona Sdk How do I spawn multiple objects and increase the number of objects every 20 seconds?

StackOverflow https://stackoverflow.com/questions/23552962

  •  18-07-2023
  •  | 
  •  

Question

I'm pretty new and have looked up my question to no avail, What I have are objects like balloons that float from bottom of the screen to the top, my problem is the spawnBallons function is only called once so only one object appears I want to call the function multiple times to spawn multiple objects and increase the number of objects spawned every 20 seconds?

    function spwanBalloons()


    local allBalloons = {"green_balloon2.png", "red_balloon.png"}
    ballons = display.newImage(allBalloons[math.random(#allBalloons)])
    ballons.x = math.random(display.contentWidth)
    ballons.y = display.contentHeight + 60

    transition.to( ballons, { time=math.random(3500-speedBump, 4500-speedBump), y=-100} )
    speedBump = speedBump + 15


end



function startGame()
    scoreText = display.newText( "Score: 0", 0, 0, "Helvetica", 22 )
    scoreText.x = centerX
    scoreText.y = display.screenOriginY + 10
    spwanBalloons()


end

I tried this timer.performWithDelay( 500, spwanBalloons, 50 ) But All it does is spawn 50 objects over a half a second, I want to spawn a random amount of object until I tell it to stop?

Was it helpful?

Solution

This should spawn 1 balloon every half second for 20 seconds, then 2 balloons every half second, etc. You can stop the timers with stopSpawnIncrease() and stopSpawn() as needed.

local spawnIncreaseTimer
local spawnNumber=0
local function spawnIncrease()
    spawnNumber=spawnNumber+1
    spawnIncreaseTimer = timer.performWithDelay( 20000, spawnIncrease)
end

function stopSpawnIncrease()
    timer.cancel( spawnIncreaseTimer )
end

local spawnTimer
function spwanBalloons()
    for i=1,spawnNumber do
        local allBalloons = {"green_balloon2.png", "red_balloon.png"}
        ballons = display.newImage(allBalloons[math.random(#allBalloons)])
        ballons.x = math.random(display.contentWidth)
        ballons.y = display.contentHeight + 60

        transition.to( ballons, { time=math.random(3500-speedBump, 4500-speedBump), y=-100} )
        speedBump = speedBump + 15
    end
    spawnTimer = timer.performWithDelay( 500, spwanBalloons )
end

function stopSpawnTimer()
    timer.cancel( spawnTimer )
end

function startGame()
    scoreText = display.newText( "Score: 0", 0, 0, "Helvetica", 22 )
    scoreText.x = centerX
    scoreText.y = display.screenOriginY + 10
    spawnIncrease() -- first call brings from 0 to 1 and starts timer
    spwanBalloons()
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top