The remainder operator does not work as I expected

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

Hi. I want to divide a number by another number and if the remainder is equal to 0, then do something.

My code is the following:

motion.x = initial_speed
var time_passed = OS.get_ticks_msec()

if time_passed % 2000 == 0:
	motion.x += added_speed
	print("current time is: ", time_passed)

I get the time elapsed since the beginning in ms and every 2 seconds (division by 2000) increase the speed by a certain amount. What am I doing wrong?

:bust_in_silhouette: Reply From: kidscancode

This will only trigger if the time is exactly a multiple of 2000. Your remainder is never zero if one frame the value is 1999 and the next it’s 2015 - since each frame is approx 16.7 ms, it’s not going to hit such a number very often. You could see this if you put that print outside the if.

If you want something to happen every two seconds, use a Timer.

func _on_Timer_timeout():
    motion.x += added_speed