Why is my KinematicBody stuttering?

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

Hi guys, I have a problem with my KinematicBody2D
It is supossed to be a ship that goes to a certain point:

Vector2 motion = (point - global_position)
move_and_slide(motion * speed)
if (global_position.distance_to(point) == 0):
do_stuff()

This is called in _process, and the do_stuff() method is not getting called. I suposse this is because of the stuttering that the body has when it reaches the point vector
Anyone has an idea of what can I do to fix this? Thanks

:bust_in_silhouette: Reply From: jgodfrey

You should never compare a floating point value to another value using ==. There are likely very minor floating point differences between the numbers that will prevent them from being exactly equal. Instead, you need to compare that they are within some small tolerance of being the same.

You can either do that yourself or use the in-built:

is_equal_approx ( float a, float b )

So, in your case:

if is_equal_approx(global_position.distance_to(point), 0):
:bust_in_silhouette: Reply From: SebSharper

I had to implement my own tolerance method, because is_equal_approx() didn’t work for me. This is a snippet of what I did:

if distance >= (stop_distance - tolerance) and distance <= (stop_distance + tolerance):
do_stuff()