Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Mathf.Acos is acting weird

Discussion in 'Scripting' started by ledrahan, Apr 8, 2015.

  1. ledrahan

    ledrahan

    Joined:
    Jul 31, 2013
    Posts:
    9
    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.x*v2.x + v1.y*v2.y + v1.z*v2.z;
    angle = Mathf.Acos(dot);
    }
     
    Last edited: Apr 8, 2015
  2. ThomasCreate

    ThomasCreate

    Joined:
    Feb 23, 2015
    Posts:
    81
    Mathf.Acos returns the angle in radians, not degrees.
     
    ledrahan likes this.
  3. ledrahan

    ledrahan

    Joined:
    Jul 31, 2013
    Posts:
    9
    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 :D i was going insane thinking why would it suddenly stop working. Thanks a lot
     
    ThomasCreate likes this.
  4. mcapousek

    mcapousek

    Joined:
    Jan 11, 2013
    Posts:
    9
    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;
     
    IAmDirt likes this.