Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice

Vector3.Angle()

Discussion in 'Editor & General Support' started by Maker16, Jun 30, 2010.

  1. Maker16

    Maker16

    Joined:
    Mar 4, 2009
    Posts:
    779
    This function gives you the angle in degrees from one vector to another. Problem is, it doesn't account for one continuous direction of rotation. If I rotate one of the vectors all the way around a given axis, the angle between the two will increase to 180, then decrease back to zero. I want to get a representation of an angle that will range from 0 to 359. How do I do that?
     
    DonPuno likes this.
  2. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    You can use the code in this thread to determine whether one vector is to the left or the right of another, given a third vector specifying the upward direction. If the vector is to the left of the reference vector, then subtract the result of Vector3.Angle from 360º to get a continuous angle:-
    Code (csharp):
    1. function ContAngle(fwd: Vector3, targetDir: Vector3, upDir: Vector3) {
    2.     var angle = Vector3.Angle(fwd, targetDir);
    3.    
    4. //The AngleDir function is the one from the other thread.
    5.     if (AngleDir(fwd, targetDir, upDir) == -1) {
    6.         return 360 - angle;
    7.     } else {
    8.         return angle;
    9.     }
    10. }
     
  3. MrVerdoux

    MrVerdoux

    Joined:
    Nov 9, 2012
    Posts:
    11
    I do it following the mathematic definition of a scalar product between two vectors (it works to me).

    float angle = Mathf.Acos(Vector3.Dot(vector1, vector2));

    Edit: now I understand your doubt... I guess you could use an auxiliar vector defined orthogonal to vector1 and vector2 (let's call it vector3), and then use two Dot products.

    if Vector3.Dot(vector1, vector3) > 0, angle is between 0 and 180.

    if Vector3.Dot(vector1, vector3) < 0, angle is between 180 and 360.

    Redit: That thing I said was stupid because the dot product would be zero because of my definition of vector3. The idea would be having a vector3 coplanar with vector1 and vector2. As it seems I'm not in my most acurate moment, I let you defining vector3 as you want... The idea of the two Dot products is still valid, while you define vector3 properly.
     
    Last edited: Nov 28, 2012