I have a timer "tmr_sendCesta
" which must be called each x seconds between 1 and 3 seconds. The problem is the timer "tmr_sendCesta
" is called only one time, and the random seconds is never updated. I need to call the function "createCesta
" each x seconds randomly.
Any idea how to do it?
function createCesta()
cesta = display.newImageRect("cesta.png", 100, 55)
cesta.x = -110
cesta.y = screenH - 110
cesta.name = "cesta"
physics.addBody( cesta, physicsData:get("cestaSmall"))
grupoCesta:insert(cesta)
transition.to(cesta, {time = 4000, x = screenW + 110})
end
function scene:enterScene( event )
local group = self.view
physics.start()
Runtime:addEventListener("touch", touchScreen)
Runtime:addEventListener( "collision", onCollision )
tmr_sendCesta = timer.performWithDelay(math.random(1000, 3000), createCesta, 0)
end
If you want call createCesta
(or randomCesta
, not sure if that's a typo or you didn't show the correct function) at random intervals, than you have to re-evaluate math.random every time. So you cannot use a looped timer, since the delay will be the same every time. You have to reschedule a new timer that computes a new random number and creates a new timer:
local function randomDelay() return math.random(1000, 3000) end
local function randomCesta()
cesta = display.newImageRect("cesta.png", 100, 55)
...
grupoCesta:insert(cesta)
transition.to(cesta, {time = 4000, x = screenW + 110})
# reschedule at new random time:
timer.performWithDelay(randomDelay(), randomCesta)
end
function scene:enterScene( event )
...
timer.performWithDelay(randomDelay(), randomCesta)
end
Presumably, you only need the return value of timer.performWithDelay
and transition.to
if you are going to cancel/resume/pause the timer or transition.