Why does this while loop make the game crash?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Marre
var screen_color = Color(1,1,1,1)

func _on_Start_button_toggled(button_pressed):
	if button_pressed == true:
		while (screen_color != Color(0,0,0,1)):
			screen_color -= Color(0.05,0.05,0.05,0)
			set_modulate(screen_color)
		$Start_button.set_disabled(true)
:bust_in_silhouette: Reply From: woopdeedoo

Probably float imprecision. At the point when the color elements reach 0, some of them could be something like -0.00000001, so the comparison evaluates to False and the color values continue to be subtracted below zero forever.

# output              comparison

0.15,0.15,0.15,1    |   False
0.1,0.1,0.1,1       |   False
0.05,0.05,0.05,1    |   False
-0,-0,-0,1          |   False    # <-- could be -0.0000001 
-0.05,-0.05,-0.05,1 |   False    #     (printing doesn't show it)
-0.1,-0.1,-0.1,1    |   False
-0.15,-0.15,-0.15,1 |   False

To work around it you could test if each of the color elements is greater than zero:

while screen_color.r > 0 or screen_color.g > 0 or screen_color.b > 0:
    # (...)

Although in your case you could probably get away with testing just one:

while screen_color.r > 0:

Yes I though of it before, but thought it was ineffecient. But to only use one color is a good idea! Thanks.

Marre | 2019-07-23 08:24