- Home /
20 is not equal to 20 while using Vector3.MoveTowards
Hello,
I use Vector3.MoveTowards to return a camera to it's original x rotation.
while(xRotation.localEulerAngles.x != patrolXRotation){
yield return new WaitForEndOfFrame();
xRotation.localEulerAngles = Vector3.MoveTowards(xRotation.localEulerAngles, new Vector3(patrolXRotation, xRotation.localEulerAngles.y, xRotation.localEulerAngles.z), Time.deltaTime * 10);
}
Well... the while loop is never ending.
Debug.Log(xRotation.localEulerAngles.x + ", " + patrolXRotation + ", " + (xRotation.localEulerAngles.x == patrolXRotation));
returns this:
20, 20, False
With target values like 20.0001 it sometimes work but not always. Any ideas?
This is the classical issue with floating point numbers. You should never compare floating point numbers resulting from computation for exact equality like that.
The proper way to handle this is to have an Epsilon constant corresponding to what you think is "close enough", and test for proximity.
Here is the obligatory link to "What every programmer should know about floating point arithmetic".
Answer by NorthStar79 · Jul 28, 2017 at 05:52 AM
there is a function for this type of calculations: https://docs.unity3d.com/ScriptReference/Mathf.Approximately.html
Answer by megabrobro · Jul 26, 2017 at 12:23 PM
I had a similar problem and I took a lazy route of just measuring the time and changing it after the time expired.
I thought about a way to fix it properly and the way I came up with is setting a buffer float for the rotation and checking if the rotation.x < startPos.x + buffer && rotation.x > startPos - buffer.x
Bit of a pain to write out in code i expect and since I am still very new I expect there is a much better way. But im fairly sure this would work
Your answer
![](https://koobas.hobune.stream/wayback/20220612131219im_/https://answers.unity.com/themes/thub/images/avi.jpg)