[SOLVED] Vector3.Angle - No value for small angles?!

Hi everybody,

I’ve just tested this on a very simple test-scene with two empty gameobjects both at same position (0, 0, 0) and with same rotation (0, 0, 0). I added a script with one line of code which is meant to debug the Vector3.Angle between the forward-vectors of the two gameobjects. It’s simply…

    void Update ()
    {
        Debug.Log (Vector3.Angle (go1.transform.forward, go2.transform.forward));
    }

Then I changed the y-rotation of gameobject2 in the editor in very small steps and noticed no difference in the debugged value until I reached a rotation of 0.0172 and Vector3.Angle gives a value of ~0.0198. Is there any explanation for this? Am I using the function wrong? :confused:

Best regards
Mat

My guess is that the function is implemented using a straightforward application of dot products and the law of cosines, which would use the inverse cosine function. Unfortunately, that function tends to have a high degree of error when the angle is close to zero, so I don’t think what you’re seeing is really all that surprising. Keep in mind, though, that you’re noticing a minimum angle of two hundredths of a degree, which still gives you 72 thousand unique positions around the full circle. For most applications, that’s enough.

I believe that for cases where this matters, one of two solutions are common: 1) Use an implementation that uses Atan2() instead of either Acos() or Asin(), or 2) conditionally switch between Acos(Dot(A, B)) and Asin(Length(Cross(A, B))) based on the size of the dot product. Acos() is poor when the dot product is close to +/-1, and Asin() is poor when the dot product is close to 0.

3 Likes

Thank you very much, Andy - this helped a lot! :slight_smile:

I decided to solve the problem (yes, it is a problem in my application ;)) by implementing a formula which uses atan2 found here. So I calculate the angle (in radians) between gameobject 1 and gameobject 2 as follows:

float angle = Mathf.Atan2 (Vector3.Magnitude (Vector3.Cross (go1.transform.forward, go2.transform.forward)), Vector3.Dot (go1.transform.forward, go2.transform.forward));

…and multiply it by Mathf.Rad2Deg to get the solution in degree afterwards.

Best regards
Mat

3 Likes