How to pause a stopwatch

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By lukas8

Hi, I already have a stopwatch in my game. But I want it to pause, when the game is paused, and resume at the same time, as it was when I paused the game, when the game is unpaused. I already got it to pause and unpause, but when I unpause it doesn’t go on from the same time. Is there any way to, so that it goes on from the correct time?

Do you use a Timer node? If so, have you looked at the time_left property? Have you tried saving and setting the remaining time with the wait_time property?

Ertain | 2020-01-23 18:27

No I’m using get_unix_time()

var time_start = 0
var time_now = 0
var game_time

func _ready():
    set_process(true)
    time_start = OS.get_unix_time()

func _physics_process(delta):
    time_now = OS.get_unix_time()
    var elapsed = time_now - time_start
    var minutes = elapsed / 60
    var seconds = elapsed % 60
    var str_elapsed = "%02d : %02d" % [minutes, seconds]
    game_time = str_elapsed

lukas8 | 2020-01-24 07:54

:bust_in_silhouette: Reply From: lukas8

I finally got it.
I had to get the the minutes and seconds, when I pause the game.
When I unpause the game, make a short delay (0.01 sec it’s important to aktivate one shot!) with a timer before getting the minutes and seconds again. Then I had to take the difference pause and unpause and then I had to do some complicated calculations so that the difference cant be nagative and not over 60. Then just go where the minutes and seconds are calculated and subtract the difference. Just add then again some calculation stuff, so that when the seconds from unpause less are then the seconds from pause. I know it is complicated as f*ck, but I don’t know how to make it more easy.

So I’m using a timer in my game to track the players best completion speed, and the way I do it is using an autoload with an incremental counter code that’s basically the following:

var frame_count = 0
var active = false

toggle(onoff):
    active = onoff

reset():
    toggle(false)
    frame_count = 0

_physics_process(delta):
    if active:
        frame_count += 1

If you’re using the built in pause function, you can just set the autoload’s pause_mode in ready. If you’re using a custom pause function, you can just use timer.toggle(x) from anywhere in your game. I know it’s not using a stopwatch, but this works well for me.

denxi | 2020-01-24 15:13

Thanks but I’m using get_unix_time()
like in my comment above
I just want to display how long the player needed to complete every level
and I think I got it working now

lukas8 | 2020-01-24 15:16