Search code examples
swifttimer

Alternative for Timers


I am having a simple game with a player, a moving background and moving walls, kinda like flappy bird. My player is able to collect a powerUp. It is transforming after and put into a special level.

I want this level to run for like 10 seconds and then call a backtransformation.

Currently I am using a timer which just calls the backtransformation after 10 seconds. I am having trouble now when the player pauses the game, the timer is still running.

--> what I found on stackoverflow is that you can't resume a timer, you can just invalidate and restart it. This would miss my target, otherwise the player pauses the game every 9 seconds and can stay in the super Level forever.

Do you guys have any idea how I can solve my problem or like an alternative to use Timers in my code?

I appreciate any help

Edit: Here is how I simply used the timer

// transform and go into super level added here
self.transform()

timer = Timer.scheduledTimer(withTimeInterval:10, repeats: false) {
                    timer in
self.backtransform()
}

Solution

  • When you start the timer record the current time as a Double using

    let start = Date().timeIntervalSinceReferenceDate
    var remaining = 10.0
    

    When the user pauses the timer, calculate the amount of time that has passed with:

    let elapsed = Date().timeIntervalSinceReferenceDate - start
    

    And the amount of remaining time for your timer:

    remaining -= elapsed
    

    If the user resumes the timer, set it to remaining, not 10 seconds.