|
|
|
|
Reply From: |
Mario |
There’s no need to reinvent the wheel here, because regular string output formatting in C (and GDScript!) already provides a mechanism for leading zeroes.
When using string formatting, you can use the placeholder %d
to signify an integer number. Formatting/inserting the number 5
with this will result in… 5
. This is not exactly what we want.
If you provide a minimum length, you’ll end up with a padded number: Formatting/inserting 5
using %2d
will get you 5
. This is close, but still not perfect.
Finally, we can add a leading zero to signify that we actually want to pad with zeroes rather than spaces: Formatting/inserting 5
using %02d
will get us 05
. This is exactly what we want! And even better, if you pass in 10
you’ll get 10
!
The rest works pretty much the way you did:
# Demo variable, 1 hour (3600 seconds), 2 minutes (120 seconds), and 3 seconds
var time = 3723 # 3600 + 120 + 3
var seconds = time % 60
time /= 60
var minutes = time % 60
time /= 60
var hours = time
# Here's all the magic happening
print("%02d:%02d:%02d" % [hours, minutes, seconds])
# Output: 01:02:03
wow this is cool, I didn’t know this!
1234ab | 2021-04-16 15:58
Thanks for explaining all this. I tried something similar like
text = "%d:%02d" % [floor($Timer.time_left / 60), int($Timer.time_left) % 60]
func _on_Timer_timeout():
countdown_time -= 1
which counts down the wait_time
of the TimerNode
(only that I won’t succeed in adding hours here…).
So I wonder, for a countdown, where would I have to put time_left
into your approach?
pferft | 2021-04-16 16:07
Since time__left
is the remaining time in seconds, you can just do something like var time = int($timer.time_left)
in my approach.
That’s it, works like a charm, thank you so much.
One last thought: it appears to print on each frame. How would I have it only printing once each second?
pferft | 2021-04-16 17:07
There are tons of possible solutions to this, you could probably just save the calculated seconds and see if they change between calls.