带有随机秒数的计时器,如何更新随机秒数?

我有一个定时器“tmr_sendCesta”,它必须每隔x秒调用一次,介于1和3秒之间。问题是定时器“tmr_sendCesta”只被调用一次,而随机秒数从未更新。我需要每隔x秒随机调用函数“createCesta”。

有什么想法吗?

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
点赞
用户2285255
用户2285255

你的调用有误,应该是:

tmr_sendCesta = timer.performWithDelay(math.random(1000, 3000), createCesta, 0)

另外,我认为使用 0 参数调用 performWithDelay 将不能达到你的目的。我认为 math.random 将不会被重新计算...(我在这里运行,每次调用之间稳定的延迟为 2078-2079 毫秒)

2014-06-02 07:56:01
用户869951
用户869951

如果你想在随机时间调用 createCesta(或 randomCesta,不确定这是否是拼写错误或者你没有展示正确的函数),那么你必须每次重新计算 math.random 。因此你不能使用循环定时器,因为每次延迟都是相同的。你必须重新安排一个新的计时器,计算一个新的随机数,并创建一个新的计时器:

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})

    # 在新的随机时间重新安排:
    timer.performWithDelay(randomDelay(), randomCesta)
end

function scene:enterScene( event )
    ...

    timer.performWithDelay(randomDelay(), randomCesta)
end

据推测,如果你需要取消/恢复/暂停计时器或过渡,只需要使用 timer.performWithDelaytransition.to 的返回值。

2014-06-02 16:54:45