Whiplash141

Pitch Yaw Roll

Feb 18th, 2019
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.35 KB | None | 0 0
  1.  
  2. void GetPitchYawRoll(
  3.     Vector3D desiredForward,
  4.     Vector3D desiredUp,
  5.     Vector3D currentForward,
  6.     Vector3D currentUp,
  7.     Vector3D yawRotorUp,
  8.     Vector3D pitchRotorUp,
  9.     Vector3D rollRotorUp,
  10.     out double yaw,
  11.     out double pitch,
  12.     out double roll)
  13. {  
  14.     Vector3D leftVector = Vector3D.Cross(yawRotorUp, currentForward);
  15.     Vector3D upVector = Vector3D.Cross(currentForward, leftVector);
  16.    
  17.     if (!Vector3D.IsUnit(ref leftVector))
  18.         leftVector.Normalize();
  19.    
  20.     if (!Vector3D.IsUnit(ref upVector))
  21.         upVector.Normalize();
  22.  
  23.     if (!Vector3D.IsUnit(ref currentForward))
  24.         currentForward.Normalize();
  25.    
  26.    
  27.    
  28.     MatrixD matrix = new MatrixD();
  29.     matrix.Forward = currentForward;
  30.     matrix.Left = leftVector;
  31.     matrix.Up = upVector;
  32.    
  33.     GetRotationAngles(desiredForward, matrix, out yaw, out pitch);
  34.     roll = 0;
  35. }
  36.  
  37. /*
  38. /// Whip's Get Rotation Angles Method v14 - 9/25/18 ///
  39. Modified to not need entire VectorMath class on 2/18/19
  40. Dependencies: AngleBetween
  41. * Fix to solve for zero cases when a vertical target vector is input
  42. * Fixed straight up case
  43. * Fixed sign on straight up case
  44. * Converted math to local space
  45. */
  46. void GetRotationAngles(Vector3D targetVector, MatrixD worldMatrix, out double yaw, out double pitch)
  47. {
  48.     var localTargetVector = Vector3D.TransformNormal(targetVector, MatrixD.Transpose(worldMatrix));
  49.     var flattenedTargetVector = new Vector3D(localTargetVector.X, 0, localTargetVector.Z);
  50.    
  51.     yaw = AngleBetween(Vector3D.Forward, flattenedTargetVector) * Math.Sign(localTargetVector.X); //right is positive
  52.     if (Math.Abs(yaw) < 1E-6 && localTargetVector.Z > 0) //check for straight back case
  53.         yaw = Math.PI;
  54.    
  55.     if (Vector3D.IsZero(flattenedTargetVector)) //check for straight up case
  56.         pitch = MathHelper.PiOver2 * Math.Sign(localTargetVector.Y);
  57.     else
  58.         pitch = AngleBetween(localTargetVector, flattenedTargetVector) * Math.Sign(localTargetVector.Y); //up is positive
  59. }
  60.  
  61. /// <summary>
  62. /// Computes angle between 2 vectors
  63. /// </summary>
  64. public static double AngleBetween(Vector3D a, Vector3D b) //returns radians
  65. {
  66.     if (Vector3D.IsZero(a) || Vector3D.IsZero(b))
  67.         return 0;
  68.     else
  69.         return Math.Acos(MathHelper.Clamp(a.Dot(b) / Math.Sqrt(a.LengthSquared() * b.LengthSquared()), -1, 1));
  70. }
Advertisement
Add Comment
Please, Sign In to add comment