Mathf.Acos is acting weird

Hi, I am having a little problem. I had a simple code that uses Mathf.Acos function, and it was working perfectly few minutes ago. I don’t know for what reason Mathf.Acos started giving me the wrong answer which is the expected angle approximately divided by 60 (dot product returns correct value). The returned values are between 0-3 instead of 0-180.

I know I could use Vector3.Dot and Vector3.Angle instead of what i used in this code but this was just a bit of vector algebra practice i was going through. Any ideas why could this happen ?

public Transform origin;
public Transform p1;
public Transform p2;
public float angle;

void Update () {
Vector3 v1 = (p1.position - origin.position).normalized;
Vector3 v2 = (p2.position - origin.position).normalized;

float dot = v1.xv2.x + v1.yv2.y + v1.z*v2.z;
angle = Mathf.Acos(dot);
}

Mathf.Acos returns the angle in radians, not degrees.

1 Like

Ohh thank you so much. So probably I confused it while tracing with Vector3.Angle. That made me think it returned the correct answer before… pff nevermind :smile: i was going insane thinking why would it suddenly stop working. Thanks a lot

1 Like

I also recommend to clamp ‘acos’ input to range [-1,+1] or you would receive NaN sometimes due to ‘float’ arithmetics. Or something like this:
if ( dot <= -1 ) return 180;
if ( dot >= +1 ) return 0;
return acos( dot ) * rad2deg;

1 Like