Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[SOLVED] 360 Angle

Discussion in 'Scripting' started by Zavalichi, Dec 11, 2018.

  1. Zavalichi

    Zavalichi

    Joined:
    Oct 13, 2018
    Posts:
    162
    Hi guys,

    I need the angle between three points.
    Angle() function return only 0 - 180 angle, but I need: AB= 90, AC = 180. AD = - 90 (or 270 )
    upload_2018-12-11_12-47-39.png
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    Use Mathf.Atan2
     
  3. Zavalichi

    Zavalichi

    Joined:
    Oct 13, 2018
    Posts:
    162
    I use x,y,z for my points
     
  4. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    There really is no difference between -90 and 90 in 3D, except if you take some up vector into account. With an up vector, you could project the points onto a plane with the up vector as normal. This projection changes the points from 3D to 2D and then, yes, you should use Mathf.Atan2.

    Another way would be to use the dot and cross products. It still requires an up vector of course:
    Code (csharp):
    1.  
    2. public static float SignedAngle(Vector3 from, Vector3 to, Vector3 up)
    3. {
    4.     float unsignedAngle = Angle(from, to);
    5.     Vector3 side = Vector3.Cross(from, up);
    6.     float sign = Mathf.Sign(Vector3.Dot(to, side));
    7.     return sign * unsignedAngle;
    8. }
    9.  
     
  5. Zavalichi

    Zavalichi

    Joined:
    Oct 13, 2018
    Posts:
    162
    Thank you
     
  6. glik

    glik

    Joined:
    Nov 14, 2012
    Posts:
    10
    Or you could use Vector3.SignedAngle(), which already does this. It returns -180 to 180. If you want it in 0 to 360 form just add 360 to the result if it is < 0.
     
    Lurking-Ninja likes this.
  7. Zavalichi

    Zavalichi

    Joined:
    Oct 13, 2018
    Posts:
    162
    Works perfect

    _angle = Vector3.SignedAngle(A-O, B-O, O);

    Thank you!