Timer.get_time_left not returning true / Timer not working properly

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Tolikowski
:warning: Old Version Published before Godot 3 was released.

Hi,

I’m struggeling a little bit with the Timer and Label right now.
My idea:
I have a timer node, that counts down from 3 to 0. on 0 the scene starts processing.
Now the visual feedback works just fine. But I also want to play a little “beep” sound effect that goes along with the changing numbers. And so far it works when 3 and 2 are displayed, but for some reason the sound effect doesn’t play on 1…

To clearify my situation, I also have a little bit of code here, that shows the fixed process:

func _fixed_process(delta):
set_text(str(ceil(get_node("Timer").get_time_left())))

if timer.get_time_left() == 3:
	sfx.play("beep")
	print("3")

if timer.get_time_left() == 2:
	sfx.play("beep")
	print("2")
	
if timer.get_time_left() == 1:
	sfx.play("beep")
	print("1")

if timer.get_time_left() == 0:
	start_clock()
	music.play()
	queue_free()
	b_spawner.set_process(true)

I really don’t know why if timer.get_time_left() == 1: doesn’t return true…
I hope someone can help me. Thanks!

:bust_in_silhouette: Reply From: eons

I don’t think that with a fixed framerate of 1/60 you will be able to get a time of exactly 1.00000000.

You need to deal with floats and do it backwards, use elif to reduce checks.

if timer.get_time_left() <= 0: #the last, this happens cut everything
    start_clock()
    music.play()
    queue_free()
    b_spawner.set_process(true)
elif timer.get_time_left() < 1 && !played_one: #dealing with floats is tricky
    sfx.play("beep")
    print("1")
    played_one = true

etc.


A better way to use the timer is to set it to 1 second and count the times the complete signal was fired, use the counter to update values and stop the timer when reached the limit.


You can use Tween or AnimationPlayer to call functions too.

Thanks a lot!
My solution for now was to set the sound effect to exactly 1 sec and check if its playing.
But the solution with the 1 sec timer sounds much better.

Tolikowski | 2017-04-10 21:04

:bust_in_silhouette: Reply From: YeOldeDM

You should be able to do all this without any polling to fixed process. Like mentioned above, use a 1-second timer, and some global var to track number of seconds left until the countdown is done. Connect the timer’s timeout signal to a method that increments your counter, sets your text, check for zero time, and anything else you need it to do when your clock goes “tick”.

var countdown = 3

func _ready():
	timer.connect("timeout", self, "_on_timer_timeout")



func _on_timer_timeout():
	if countdown <= 0:
		go()
	else:
		countdown -= 1
		sfx.play('beep')
		set_text(str(countdown))
		print(countdown)



func go():
	timer.stop()
	start_clock()
	music.play()
	queue_free()
	b_spawner.set_process(true)