Hi community,
I’m stuck with a really weird timer.pause() and timer.resume() problem.
I got a square jumping on the ground every 2 seconds using timer.performWithDelay and applyFore for the jump.
When I try to pause the timer, and then resume, it sometimes happens that the resuming will not continue where it paused, but perform the applyForce immediately.
It happens more often, when I try to pause in the first 1 second of the 2 second sequence.
I’ve also measured the actual milliseconds between the jumps and it varies between 900 and 2000 ms (where it should be always 2000ms ± 30ms).
Please help, I’m stuck on the problem for days now…
See below for the code - if you try that yourself:
First, please watch how the square jumps up and down to see that it happens about every 2 seconds without pauseing.
Then, try to pause the game (just click anywhere) when the square is on the way up (also see attachment for the exact moment).
Then wait a bit and resume (again, click anywhere) and check if the square jumps earlier than it should be.
If you don’t see the problem immediately, try to pause and resume several times.
Here’s the code:
local physics = require "physics" physics.setScale( 90 ) physics.start() local startPauseTime = 0 local endPauseTime = 0 local totalPauseTime = 0 local lastForceTime = 0 local currentForceTime = 0 ground = display.newRect( -100,display.contentHeight-82, display.contentWidth+100, 82+100 ) ground:setFillColor(0,0.3,0) ground.anchorX = 0 ground.anchorY = 0 physics.addBody( ground, "static", { friction=0.3} ) brick = display.newRect(100,100,100,100) --brick.anchorY = 0 brick.x = display.contentWidth / 2 brick.y = display.contentHeight/2-35 physics.addBody( brick, "dynamic", {density = 1.0, friction=0.9}) testTimer = timer.performWithDelay(2000, function () print ("Time between applyForce: " .. system.getTimer() - lastForceTime - totalPauseTime) totalPauseTime = 0 --print ("Brick y position: "..brick.y) brick:applyForce(0, -250, brick.x, brick.y) lastForceTime = system.getTimer() end,0) bg = display.newRect( -100,-100, display.contentWidth, display.contentHeight ) bg.x, bg.y = display.contentWidth / 2, display.contentHeight / 2 bg:setFillColor(0.3,0.3,0.3) bg:toBack() local function pauseTestTimer() local t = timer.pause(testTimer) --print ("pause time: "..t) startPauseTime = system.getTimer() end local function resumeTestTimer() local t = timer.resume(testTimer) --print ("resume time: "..t) endPauseTime = system.getTimer() totalPauseTime = endPauseTime - startPauseTime --print ("Time between Start and End of Pause: " .. totalPauseTime) end bg:addEventListener("touch", function(event) if (event.phase=="began") then if (pause==true) then pause=false resumeTestTimer() physics.start() return true else pause=true pauseTestTimer() physics.pause() return true end elseif (event.phase=="ended") then return false end end)