Formatting a timer

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

i am making a stopwatch for a game i am working on but i cannot figure out how to changhe the formatting
the code is bellow

extends Control

var time_elapsed := 0.0
var minutes := time_elapsed / 60
var seconds := fmod(time_elapsed, 60)
var milliseconds := fmod(time_elapsed, 1) * 100
var time_string := "%02d:%02d:%02d" % [minutes, seconds, milliseconds]

func _process(delta: float) -> void:
	time_elapsed += delta
	$Speedclock.text = str(time_elapsed) 

i am trying to format the time elapsed to the formatting of time string

how would i do this?

1 Like
:bust_in_silhouette: Reply From: rhennig

I’m not sure if I got your question but if you want to format like timestring you should put it as the output, like:

var time_elapsed := 0.0
var minutes
var seconds
var milliseconds
var time_string

func _process(delta: float) -> void:
	time_elapsed += delta
	minutes = time_elapsed / 60
	seconds = fmod(time_elapsed, 60)
	milliseconds = fmod(time_elapsed, 1) * 100
	time_string = "%02d:%02d:%02d" % [minutes, seconds, milliseconds]
	$Speedclock.text = time_string
1 Like
:bust_in_silhouette: Reply From: joeyq

You assumed the variables minutes, seconds and milliseconds will update as you update the variable time_elapsed in the process function, but they will only update in the main game loop when they are also put in the main game loop inside either methods Node._process() or Node._physics_process().
Also I have never seen string ‘mm:ss:ms’. If I saw that in a game I would think it would represent ‘hh:mm:ss’, I would suggest using ‘hh:mm:ss.ms’ or ‘mm:ss.ms’ in a function, but that’s just my opinion.
I would write your code something like this:

extends Control

var time_elapsed:float = 0.0
## I assume Speedclock is a child node of type Label here.
onready var speed_clock: Label = $"Speedclock"

func _process(delta: float) -> void:
	time_elapsed += delta
	speed_clock.text = seconds2hhmmss(time_elapsed)

func seconds2hhmmss(total_seconds: float) -> String:
	#total_seconds = 12345
	var seconds:float = fmod(total_seconds , 60.0)
	var minutes:int   =  int(total_seconds / 60.0) % 60
	var hours:  int   =  int(total_seconds / 3600.0)
	var hhmmss_string:String = "%02d:%02d:%05.2f" % [hours, minutes, seconds]
	return hhmmss_string