Question about timer (SOLVED)

how come this isn’t working?
if self.timer == 3 then
print(“test”)
end

I have self.timer = 0 in the init function and
this in the update function

if self.timer >= 0 then
self.timer = math.max(self.timer + dt, 0)
gui.set_text(gui.get_node(“my_text_node”), tostring(self.timer))
end
if self.timer == 3 then
print(“test”)
end

this works btw but not the is equal to
if self.timer >= 3 then
print(“test”)
end

A) Because of floating point precision.

B) Because your ‘dt’ may not be exactly 1/60th of a second every frame. (Or 1/30th, 1/20th, etc.)

Your self.timer will never exactly equal 3. It may be 3.0000001. It may go from 2.985333 on one frame, to 3.00199966666667 on the next, skipping over 3.

Whenever you’re dealing with decimal numbers, you should use >= or <=.

2 Likes

There is also a timer feature built into Defold, so you don’t have to keep track of simple timers like this yourself if you don’t want to.

2 Likes

I recommend using the timer feature @ross.grams mentioned. It is lightweight and straightforward.

1 Like

@ross.grams I’m using the timer feature now, thanks for the link and explanation.

2 Likes