计时器在场景 Corona SDK 中调用了两次
Timer called twice in scene Corona SDK
我的代码中有一个计时器,每 1 秒生成一次对象。
当物体与 "deathObj" 碰撞时,场景从场景 2 变为场景 1。
但是当从 scene1 我 return 到 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
当您从场景 2 切换到场景 1 时,尝试暂停或取消计时器。
第二次打完就用这个解决了
timer.cancel(spawnTimer)
spawnTimer = timer.performWithDelay(seconds, spawn, -1)
跟踪你的代码,你的目的似乎太多了。为了您自己的理智以及帮助那些想帮助您的人,让您的代码缩进正确非常重要。
如果我没看错你的代码,你的计时器在 "if - then - else" 语句之外,该语句测试你是处于 "will" 阶段还是 "did" 阶段。 scene:show() 事件触发两次,一次在屏幕外 ("will"),一次在屏幕上 ("did")。由于您的计时器在 if 之外,它将执行两次。
我的代码中有一个计时器,每 1 秒生成一次对象。 当物体与 "deathObj" 碰撞时,场景从场景 2 变为场景 1。 但是当从 scene1 我 return 到 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
当您从场景 2 切换到场景 1 时,尝试暂停或取消计时器。
第二次打完就用这个解决了
timer.cancel(spawnTimer)
spawnTimer = timer.performWithDelay(seconds, spawn, -1)
跟踪你的代码,你的目的似乎太多了。为了您自己的理智以及帮助那些想帮助您的人,让您的代码缩进正确非常重要。
如果我没看错你的代码,你的计时器在 "if - then - else" 语句之外,该语句测试你是处于 "will" 阶段还是 "did" 阶段。 scene:show() 事件触发两次,一次在屏幕外 ("will"),一次在屏幕上 ("did")。由于您的计时器在 if 之外,它将执行两次。