Delta timer works on >= but not ==, why?

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

I have some code to set a delta timer to control the shooting function. It works as expected, but one strange thing is that when I set the if condition to if delta_timer == 0:then the code does not work. I don not under stand why >= works but not ==? even with >=, the process stops at shoot_timer = 0.2. Thank you.

Var delta_timer = 0

func shoot_bullet(delta):
    playerAnimation.play("Shoot")
    delta_timer += delta
    print(delta_timer)
    if delta_timer >= 0.2:
    	    shoot_bullet()
    		delta_timer = 0
    		set_animation_finish()
    
:bust_in_silhouette: Reply From: rakkarage
if is_equal_approx(delta_timer, 0.2):

Thank you, your suggestion works perfect for me.

Idleman | 2020-09-23 07:34

:bust_in_silhouette: Reply From: exuin

I don not under stand why >= works but not ==?

delta is the amount of time elapsed since the last frame. It’s always going to be greater than 0, and since you add delta to delta_timer before the if statement, it will never be equal to 0.

even with >=, the process stops at shoot_timer = 0.2.

I’m not exactly sure what you mean by this, but if you’re asking why the animation stops at 0.2 seconds, it might be because you’re calling set_animation_finish() after 0.2 and resetting the timer.

Another way to handle this would be to make a Timer node that lasts for 0.2 seconds and plays the animation every time the Timer times out.

Thank you for answering my question. I mean when I use >= 0.2, the code works, but if I use ==0.2 the code does not. First I thought that may be it is because the delta_timer is calculated by the frame and does not rest exactly value of 0.2, but if I print out the timer, it stops on 0.2 exactly, so I don’t know why timer == 0.2 does not work.

Idleman | 2020-09-23 07:33

Oh, alright. Your question said if delta_timer == 0: so I was confused.

exuin | 2020-09-23 07:35

:bust_in_silhouette: Reply From: Zylann

I would actually suggest you DONT use any form of equality operation on delta_timer. Using >= is actually correct, because delta can take fluctuating values depending on your FPS (depends where you take that delta from, tho). You never really know by how much it will “overshoot” past 0.2.

You have a really good point, I would switch back using >=, thank you for your advice.

Idleman | 2020-09-23 12:23