Whiplash141

Get Rotation Angles

Apr 13th, 2018
799
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.36 KB | None | 0 0
  1. /*
  2. /// Whip's Get Rotation Angles Method v12 - 2/16/18 ///
  3. Dependencies: VectorAngleBetween()
  4. * Fix to solve for zero cases when a vertical target vector is input
  5. * Fixed straight up case
  6. * Fixed sign on straight up case
  7. * Converted math to local space
  8. */
  9. void GetRotationAngles(Vector3D targetVector, IMyTerminalBlock reference, out double yaw, out double pitch)
  10. {
  11.     var localTargetVector = Vector3D.TransformNormal(targetVector, MatrixD.Transpose(reference.WorldMatrix));
  12.     var flattenedTargetVector = new Vector3D(localTargetVector.X, 0, localTargetVector.Z);
  13.    
  14.     yaw = VectorAngleBetween(Vector3D.Forward, flattenedTargetVector) * Math.Sign(localTargetVector.X); //right is positive
  15.     if (Math.Abs(yaw) < 1E-6 && localTargetVector.Z > 0) //check for straight back case
  16.         yaw = Math.PI;
  17.    
  18.     if (Vector3D.IsZero(flattenedTargetVector)) //check for straight up case
  19.         pitch = MathHelper.PiOver2 * Math.Sign(localTargetVector.Y);
  20.     else
  21.         pitch = VectorAngleBetween(localTargetVector, flattenedTargetVector) * Math.Sign(localTargetVector.Y); //up is positive
  22. }
  23.  
  24. double VectorAngleBetween(Vector3D a, Vector3D b) //returns radians
  25. {
  26.     if (Vector3D.IsZero(a) || Vector3D.IsZero(b))
  27.         return 0;
  28.     else
  29.         return Math.Acos(MathHelper.Clamp(a.Dot(b) / Math.Sqrt(a.LengthSquared() * b.LengthSquared()), -1, 1));
  30. }
Advertisement
Add Comment
Please, Sign In to add comment