Vector3 equal test with own tolerance, how?

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


I would like to compare two Vector3 for equality with my own tolerance e.g. 0.001: (2.000084, 0, 0) with (1.999969, 0, 0)

The method .is_equal_approx() doesn’t do it.

Do I have to write my own GDscript method?



:bust_in_silhouette: Reply From: timothybrentwood

I don’t know of any built-in functions that mimic is_equal_approx() where you can supply your own epsilon so you would need to write your own method.

Edit: If you don’t know how to write the function this should work:

func vectors_approx_equal(v1 : Vector3, v2 : Vector3, epsilon : float) -> bool:
	var difference = v1 - v2
	return (difference.x < epsilon) and (difference.y < epsilon) and (difference.z < epsilon)

Hi timothy,

thank you for your answer, and your nice code.

All the best


MikeMikeMike | 2021-08-19 09:12

Hi timothy,

I have updated your code, I think you have forgotten abs(). Now this seams to work:

func vectors_approx_equal( v1 : Vector3, v2 : Vector3, epsilon : float ) -> bool:
	var diff = v1 - v2
	return abs( diff.x ) < epsilon and abs( diff.y ) < epsilon and abs( diff.z ) < epsilon

Thanks again


MikeMikeMike | 2021-08-19 19:22