- Home /
How precise is unity with it´s transforms?
I need to check whether 2 objects have the same direction (are parallel). This is what I do:
Vector3 myForward = transform.TransformDirection(Vector3.forward);
Vector3 otherForward = otherCollider.transform.TransformDirection(Vector3.forward);
if (Vector3.Dot(myForward, otherForward) == 1)
{
Debug.Log ("we are aligned (rotation)");
}
else
{
Debug.Log ("we are NOT aligned (rotation)" + Vector3.Dot(myForward, otherForward));
}
Now I placed two object in the scene with rotation 0,0,0 in the inspector. (also scale 0,0,0 for both and position 0,0,0 for one and 0,0.45,0 for the other). This gives me the debug line "we are aligned (rotation)". So it worked.
Then I chance the rotation of both object in the inspector to 315,0,0 and this gives me the debug line "we are NOT aligned (rotation)0.9999999". So it did not work.
What is going on? Are they truely not facing the same direction or should I use some rounding function on the result? Or Am I doing something completely wrong here?
Answer by GerryM · Feb 14, 2013 at 07:30 PM
This is basically a float precision problem. Never compare two floats (the return of the dot function) and your 1 without considering some internal rounding errors. Try something like:
if (Math.Abs(Vector3.Dot(myForward, otherForward) - 1f) < 0.0001f)
Furthermore, rotation data is internally stored as quaternions, what you see in the inspector (vector3) therefore has a further conversion error.
Thanks to the two of you. I´m going to round then to 3 or 4 decimal places.
Answer by Eric5h5 · Feb 14, 2013 at 07:30 PM
You should round at least a little, because of floating point imprecision. By the way, you can just say transform.forward
instead of transform.TransformDirection(Vector3.forward)
.