【问题标题】:Timer with random seconds ¿How to update the random seconds?带有随机秒数的计时器¿如何更新随机秒数?
【发布时间】:2014-06-02 03:20:55
【问题描述】:

我有一个计时器“tmr_sendCesta”,必须在 1 到 3 秒之间每隔 x 秒调用一次。问题是定时器“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

【问题讨论】:

    标签: random timer lua coronasdk 2d-games


    【解决方案1】:

    如果您想随机调用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})
    
        # reschedule at new random time:
        timer.performWithDelay(randomDelay(), randomCesta)
    end
    
    function scene:enterScene( event )
        ...
    
        timer.performWithDelay(randomDelay(), randomCesta)
    end
    

    大概,如果您要取消/恢复/暂停计时器或转换,您只需要timer.performWithDelaytransition.to 的返回值。

    【讨论】:

    • 谢谢!!这正是我所需要的,正确的方法是“createCesta”我在问题中有“randomCesta”,因为我正在尝试另一种方式。一个问题,enterScene 函数中的计时器只调用一次,对吗? @Schollii
    • 是的,它只被调用一次,在场景出现在屏幕上之后。
    【解决方案2】:

    你的调用不正确,应该是:

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

    另外,我认为使用 0 参数调用 performWithDelay 不会达到您的目的。我认为 math.random 不会再次计算...(我跑到这里,调用之间有 2078 - 2079 毫秒的稳定延迟)

    【讨论】:

    • 对另一种方式有什么想法吗? @RSC
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 2013-07-14
    • 1970-01-01
    • 2019-10-16
    • 2014-08-01
    • 1970-01-01
    相关资源
    最近更新 更多