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

Vector3.Angle functions are giving unexpected results

Discussion in 'Scripting' started by NeoKuro, Dec 24, 2017.

  1. NeoKuro

    NeoKuro

    Joined:
    Jan 30, 2015
    Posts:
    20
    Apologies if this is the wrong forum, or I am missing something entirely obvious. But I'm attempting to get the angle between the transform.Position of one object (A), and the transform.position of a second object (B).

    Now, I know that the angle should be at, or around, 90 degree - and whilst the game is 3D, I have eliminated the y component (I don't care how much above or below me it is).

    Object A is located at; 62.2, Y, 0.0
    Object B is located at; 398, Y, 0.0

    There is no rotation applied to either object, and I have tried;
    Vector3.SignedAngle(A,B, A.forward)
    Vector3.SignedAngle(A,B, A.up)
    Vector3.SignedAngle(A,B, A.right)
    Vector3.SignedAngle(A,B, Vector3.up)
    Vector3.SignedAngle(A,B, Vector3.right)
    Vector3.SignedAngle(A,B, Vector3.forward)
    Vector3.Angle(A,B)
    Vector2.Angle(A,B)
    ....

    And they ALL return an angle of '0'. Its almost as if the 'forward' direction is to the 'right' of Object 'A'.

    I know the angle SHOULD be at around 90 degree. But it obviously is not...am I missing something crucial?
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    You have taken the position, instead of the direction(s).
    Here is some sample code, virtually identical to the manual page. I ran it as a test with your values and got 90/-90 (depending on not signed/signed):
    Code (csharp):
    1.  
    2. Vector3 direction = objB.position - objA.position;
    3. float angle = Vector3.Angle(direction, objA.forward);
    4. print("angle = " + angle);
    5.  
    6. angle = Vector3.SignedAngle(direction, objA.forward, Vector3.up);
    7. print("signed angle = " + angle);
    8.  
    Manual pages (with example): https://docs.unity3d.com/ScriptReference/Vector3.SignedAngle.html
    https://docs.unity3d.com/ScriptReference/Vector3.Angle.html
     
  3. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    It's better not to edit out your question like that, because they come up in searches. Believe it or not, most of us have made the same mistake.
     
  4. NeoKuro

    NeoKuro

    Joined:
    Jan 30, 2015
    Posts:
    20
    Ahhh ok. Hopefully my silliness will help others down the line haha

    Even though all it took to solve it was a look at the Manual on Vector3.Angle haha
     
  5. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    :) Glad you got it fixed, all the same.