Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Question Mathf.Acos not behaving as expected

Discussion in 'Scripting' started by SolAgurken, May 10, 2024.

  1. SolAgurken


    May 19, 2020
    I'm having a little trouble with my code. I'm using the Mathf.Acos function but it only returns Nan. Whats the issue?
    Heres my code:

    AB = 1.5f;
    BC = 2f;
    AC = 3f;

    float angleB = (Mathf.Pow(AB, 2) + Mathf.Pow(BC, 2) - Mathf.Pow(AC, 2)) / 2 * AB * BC;
    angleB = Mathf.Acos(angleB) * Mathf.Rad2Deg;

  2. Bunny83


    Oct 18, 2010
    Acos, by definition, will return a NaN value whenever the input is below -1 or above 1. It's enough when you are a tiny bit below / above. So just make sure the value you pass to Acos is in the proper range. That's why most methods that use Acos will clamp the value. Like the Angle method.

    ps: Note that this part:
    Code (CSharp):
    1.  / 2 * AB * BC;
    Does NOT divide by AB and BC as division and multiplication are on the same level and are evaluated left to right. So you only divide by 2 here. You actually multiply by AB and BC which you probably didn't want to do. Either use division 3 times, or put brackets
    Code (CSharp):
    1.  / (2 * AB * BC);