Search Unity

Need help understand a function uses vector maths

Discussion in 'Scripting' started by welliam, Aug 31, 2014.

  1. welliam

    welliam

    Joined:
    Oct 16, 2010
    Posts:
    18
    Hi,
    Following this tutorial there was this function "FindAngle", I followed the vector maths clip many times but I dont understand why the tutor uses Vector3.Angle, Vector3.Cross, then Mathf.Sign(Vector3.Dot in that order so I appreciate if any one put a light on it for me.

    Code (CSharp):
    1. float FindAngle (Vector3 fromVector, Vector3 toVector, Vector3 upVector)
    2. {
    3. // Create a float to store the angle between the facing of the enemy and the direction it's traveling.
    4. float angle = Vector3.Angle(fromVector, toVector);
    5. // Find the cross product of the two vectors (this will point up if the velocity is to the right of forward).
    6. Vector3 normal = Vector3.Cross(fromVector, toVector);
    7. // The dot product of the normal with the upVector will be positive if they point in the same direction.
    8. angle *= Mathf.Sign(Vector3.Dot(normal, upVector));
    9. // We need to convert the angle we've found from degrees to radians.
    10. angle *= Mathf.Deg2Rad;
    11. return angle;
    12. }
    Thanks
     
  2. Fraconte

    Fraconte

    Joined:
    Dec 6, 2013
    Posts:
    327
    I think it's using that code to just know if the angle is on the right or on the left side of the forward direction.
    If the angle is on the right then the cross product points up. With the dot you can tell if the cross is pointing up because it is positive if the two vectors are pointing in the same direction (upVector indicates the up direction). Finally you make the angle positive or negative by multiplying it by the sign (+-1) of the dot product.
     
  3. welliam

    welliam

    Joined:
    Oct 16, 2010
    Posts:
    18
  4. Fraconte

    Fraconte

    Joined:
    Dec 6, 2013
    Posts:
    327
    In theory if the two vectors of the dot are perfectly parallel to each other and their magnitude is equal to 1, then the value would be +-1 so there would be no need. But the dot product can have any values depending on the dimensions and direction of the two vectors and perhaps it's not always reliable. So the the Mathf.Sign can help in some cases even if you can just omit it in many other.
     
  5. welliam

    welliam

    Joined:
    Oct 16, 2010
    Posts:
    18
    If you have the time can you draw a picture of the several vector operations above ? I am not able to figure it out and perhaps the draw can help.
     
  6. Fraconte

    Fraconte

    Joined:
    Dec 6, 2013
    Posts:
    327
  7. welliam

    welliam

    Joined:
    Oct 16, 2010
    Posts:
    18
    many thanks Fraconte