Vector2(0, 0) is not equal to Vector2(0, 0) for some unknown reason.

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

I have a function like this -

func move_interpolated(direction : Vector2, vel_rate : float, floor_normal : = Vector2.ZERO):
	direction = direction.normalized()
	var target = direction * speed
	velocity = velocity.linear_interpolate(target, vel_rate)
	move_and_slide(velocity, floor_normal)
	return velocity

Velocity is a property. I am trying to use it in an FSM like this (FSM not relevant) -

if target.velocity == Vector2.ZERO:

But it never seemed to work. After hours of testing I found out that 0 ≠ 0 for some reason.

I found out by trying this -

print(target.velocity.x == 0)
print(target.velocity.y == 0)

The output showed false correctly the first time, but even after velocity reached (0, 0) it remained false. This was done in Physics Process.
I have no clue how to proceed and any help is appreciated.

:bust_in_silhouette: Reply From: wombatstampede

That’s the magic of floating point values. Comparing two floating point values for equality often fails. Most of the time it is better to work with error margins.

You can be lucky when the values have been initialized from the same source/assignment and not changed since then. But it is still risky.

Googling brought up this here:

But opposed to the source above I often work with error margins when comparing FP values. This works IMHO as long as you roughly know what values to expect.

So to compare a single value to 0 you could do:

if abs(vec2.x) < 0.000001:

The number is an arbitrary low number which should be somwhere above the floating point resolution for values in that range but low enough to satisfy your requirements.

If you want to compare to vectors then you could do:

  if (vec2a - vec2b).length() < 0.000001:

This works best if both vectors stay in a certain number range (i.e. normalized vectors). But often enough you can also make the allowable margin bigger in this case.

Naturally it is best to define & use some constant for i.e. 0 comparisons.

Thank you. I’ll test this out tomorrow when I get back to my PC.

Edit: It worked. Thanks!

GooglyCoffeeMeat | 2019-10-23 14:20