Hi,
Could someone please help me to understand why if I compare 2 values (“x” values ) from two different vectors (one Vector2 and the other Vector4), even they are equal (0,8 for example) Unity considers they are different?
This is part of the code:
private Vector2 newOffset;
private Vector4 animationLimits;
private float totalCol;
private float walkAnimationMin = 5;
private float walkAnimationMax = 14;
private float tempValue;
private Vector2 newOffset;
private Vector2 currentOffset;
textureScale = gameObject.renderer.material.mainTextureScale;
totalCol = Mathf.Abs(1 / textureScale.x);
totalRow = Mathf.Abs(1 / textureScale.y);
tempValue = walkAnimationMax / totalCol;
animationLimits.z = Mathf.Sign(textureScale.x) * (tempValue - Mathf.Floor(tempValue));
.....
currentOffset = gameObject.renderer.material.mainTextureOffset;
newOffset.x = currentOffset.x + textureScale.x;
if (newOffset.x > animationLimits.z){
...
}
Sorry if it is too confusing. Basically I am following the tutorial about Evac City and I am modifying the script for animating the player, for learning purpose.
Thanks
The two values have to be totally identical, not just the first decimal place.
–Eric
Thanks Erick. This means, that even in the Debug.Log both values are equal (0,8 for example) Unity is adding some extra decimals when I made all that calculation?
Edit: I just did some test, like this:
Debug.Log(newOffset.x - animationLimits.z);
and even both values are in theory 0,8 the result is something E-08.
Why this happens? I made the calculation in my calculator and the results are both 0,8 without any extra decimal.
Thanks
Regards
Floating point math isn’t 100% exact.
–Eric
Never, ever, ever compare floating point numbers for equality. Always use an approximation function. Try Mathf.Approximately Unity - Scripting API: Mathf.Approximately
I’m trying to compare two vectors (vector3) and if use != or Mathf.Approximately the result is ever the exact same, ever false (T_T) xD
Some idea?
Edit: finally i have found a solution, isn’t very elegant but…works (^_^)
function CompararVec () : boolean
{
// i only need to compare x and z
if ( System.Math.Round(vecOrig.x, 1) == System.Math.Round(vecDest.x, 1)
System.Math.Round(vecOrig.z, 1) == System.Math.Round(vecDest.z, 1) )
return true;
else
return false;
}
I try ,
Vector.Distance(pointa,pointb)<=0.1
,
it’s work and it is fast than,
Mathf.Approxmatelt(…
So I use,
Vector.Distance(pointa,pointb)<=0.1 , this type
1 Like