Let me explain first. I create a ball, a goal and a bottomLine (if ball touch bottomLine game over) in scene:create (composer)
local ball local goal local bottomLine --scene:create --create a ball ball = display.newCircle( centerX, centerY-300, 20 ) ball.fill = loads.ball\_1 ball.id = "ball" physics.addBody( ball, { density=0.8, friction=1.0, bounce=1.0, radius=20 } ) ball.strokeWidth = 1 ball:setStrokeColor( 0 ) sceneGroup:insert( ball ) ball.collision = onLocalCollision ball:addEventListener( "collision", ball ) --create a goal goal = display.newRect( centerX+50, centerY+180, 100, 15 ) goal:setFillColor( 24, 192, 130 ) goal.strokeWidth = 2 goal:setStrokeColor( 0 ) goal.id = "goal" physics.addBody( goal, "static" ) sceneGroup:insert( goal ) goal.collision = onLocalCollision goal:addEventListener( "collision", goal ) -- create a bottom line bottomLine = display.newRect( centerX, center+400, 768, 30 ) bottomLine.id = "b" physics.addBody( bottomLine, "static", { friction=1.0, bounce=0 } ) sceneGroup:insert( bottomLine ) bottomLine.collision = onLocalCollision bottomLine:addEventListener( "collision", bottomLine )
Then at top in the composer area to code functions I put the “onLocalCollision()”.
--forward declarations local tmr --next level function local function nextLevel( event ) composer.gotoScene( "scenes.level\_2" ) end --collision function local function onLocalCollision( self, event ) if ( event.phase == "began" ) then if self.id == "ball" and event.other.id == "goal" then event.contact.bounce = 0 ball.fill = loads.ball\_2 tmr = timer.performWithDelay( 3000, nextLevel ) elseif self.id == "ball" and event.other.id == "b" then composer.gotoScene( "scenes.reload" ) end end end
and in scene:hide “will” phase I check if the timer is nil, and if not, cancel and nil timer. I code a print statement for “tmr” to see in the console if I get a table or nil, and I get nil, yeah!!
-- hide() function scene:hide( event ) local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then -- Code here runs when the scene is on screen (but is about to go off screen) if tmr ~= nil then timer.cancel( tmr ) tmr = nil end elseif ( phase == "did" ) then -- Code here runs immediately after the scene goes entirely off screen print( tmr ) end end
but, in simulator, I go to level_2 if “ball” collide with “goal”, I go to reload and back to level_1 if “ball” collide with “b” (bottomLine), but if I’m playing with my ball in level_1 the timer activates on its own and takes me to level_2 although the “ball” does not collide with the “goal”.
I know it is scope problem or something wrong with my timer.
Thanks in advance
DoDi