Vector3.Angle returning wrong values for vectors with small components

I tried to get the angle between two Vector3’s using Vector3.Angle and got a return value I didn’t expect.

The two vectors where (1, 0, 0) and (0.00001, 0, 0) and the angle between the two should obviously be 0. However, Vector3.Angle returns 90.

This isn’t related to the length difference of the vectors, Vector3.Angle also reports the angle between (0.00001, 0, 0) and itself as 90. On the other hand, the difference between (1000000, 0, 0) and itself or (1, 0, 0) is reported correctly as 0.

Is this related to the algorithm used by Vector3.Angle or a bug? The documentation doesn’t say anything about it expecting only vectors in a specific range or only normalized ones.

Normalizing probably is the issue here. The documentation on Vector3.Normalize states:

If the vector is too small to be normalized a zero vector will be returned.

Vector3.Angle probably normalizes the input vectors, calculating the angle between (1, 0, 0) and (0, 0, 0). Vector3.Angle also seems to return 90 when either of its input vectors has zero length.

I ran into this problem as well, so I wrote my own angle functions.

    //This returns the angle in radians
    public static float AngleInRad(Vector3 vec1, Vector3 vec2)
    {
    	return Mathf.Atan2(vec2.y - vec1.y, vec2.x - vec1.x);
    }

    //This returns the angle in degress
    public static float AngleInDeg(Vector3 vec1, Vector3 vec2)
    {
    	return AngleInRad(vec1, vec2) * 180 / Mathf.PI;
    }

See Atan2 for more details.