在场景中定时器被调用了两次,使用的是Corona SDK。

我在代码中设置了一个定时器,每一秒就会生成一个对象。 当一个对象与“deathObj”发生碰撞时,场景会从scene2切换到scene1。 但是,当我从scene1返回scene2时,定时器会被调用两次,如果重试,就会被调用4次等等... 如何使定时器只调用一次呢?

function scene:show( event )

local sceneGroup = self.view
local phase = event.phase

if ( phase == "will" ) then

    elseif ( phase == "did" ) then
        local function spawn()
            --things for spawn the object
        end

    end

    local function deathObjCollision(self, event)
        if (event.phase == "began" ) then
        composer.gotoScene("scene1")
        end
    end

    deathObj = display.newRect(300,1900,1600,100)
    physics.addBody(deathObj, "static", {density=1.0, friction=0.5, bounce=0.3})
    deathObj.collision = deathObjCollision
    deathObj:addEventListener( "collision", deathObj )

    spawnTimer = timer.performWithDelay(1000, spawn, -1)

    end
end
点赞
用户5244764
用户5244764

尝试在从场景2切换到场景1时暂停或取消计时器。

2015-08-19 19:31:39
用户5230245
用户5230245

当游戏第二次结束时,我使用以下方法解决。

timer.cancel(spawnTimer)
spawnTimer = timer.performWithDelay(seconds, spawn, -1)
2015-08-19 20:54:53
用户1870706
用户1870706
**跟踪你的代码,似乎你有太多的结束语。** 为了保持清晰和帮助愿意帮助你的人, 让你的代码缩进正确非常重要。

如果我正确地阅读了你的代码,你的计时器在“will”阶段或“did”阶段的“if-then-else” 语句之外。场景:show()事件会触发两次,一次在屏幕外(“will”),一次在它显示后(“did”)。由于你的定时器在if之外,它会执行两次。
2015-08-31 04:30:45