Sometime compare return wrong.

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

Normally this code works fine.
After a few times it will be stuck because linear_velocity.y == 0 never returns True but the result of linear_velocity.y is always logged out to 0.

:bust_in_silhouette: Reply From: jgodfrey

You should never compare floating point values via ==. That’s because minor floating point errors will cause the equality to fail sometimes - just as you’re experiencing.

Based on what you’re doing, you typically want to verify that some value is “sufficiently close” to some other value.

In your case, you could do something like:

if abs(linear_velocity.y) < 0.001:

… or something similar…

is_equal_approx() and Vector2.is_equal_approx() were created for just this situation.

kidscancode | 2020-05-08 18:10

good tip - thanks.

jgodfrey | 2020-05-08 21:26