Vector2 Comparison Operation Not Working with If Statement

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

HI!

Godot 3.2.2 stable on macOS

I am trying to lerp a Vector2 during a physics process and tell the process to stop once the interpolation reaches the B value: Vector2(0,0). For some reason, the “if” statement comparing offset == Vector2(0,0) does not seem to be working. When I print(offset), I can see that offset does equal one of the compared vector values, but it never runs the code of the if statement; in this case lerping = false.

var shaking = true
var lerping = false


func _physics_process(delta):
	if lerping == true:
		offset = lerp(offset, Vector2(0,0), .3)

	if offset == Vector2(0,0) or offset == Vector2(-0,0) or offset == Vector2(0,-0) or offset == Vector2(-0,-0):
		lerping = false
	
	if shaking == true:
		offset += Vector2(rand_range(-25,25), rand_range(-25,25))* delta
		lerping= true
	
	print('lerping: ', lerping)
	print('offset: ',offset)


func _on_ShakeTimer_timeout():
	shaking = false

Here are the output prints:

...
lerping: True
offset: (0, 0)

Does anyone know what I am doing wrong? I will eventually be using this to set _process = false

:bust_in_silhouette: Reply From: jgodfrey

I’d guess that your vector isn’t actually 0,0, even though it may be very close (and likely close enough to print out as 0,0)…

Really, you shouldn’t ever do an equality comparison to non-integer values as the results are bound to be inconsistent at best…

The Vector2 class has a function for just this issue… Try something like this:

offset.is_equal_approx(Vector2(0,0))

That’ll ensure that your vector is very near the comparison vector (in this case 0,0), without requiring it to be exact

Most likely the case. The prints by default won’t show the fullest precision, you have to force a higher precision to see the far out zeroes that may exist.

For example:

var v = Vector2(0, 0.0000001)

printt(v, v == Vector2(0, 0))
print("Y with higher precision format: ", "%0.10f" % v.y)

avencherus | 2020-08-29 16:34