Created
February 20, 2021 09:25
-
-
Save yesseecity/1ace0bf0659322f197bb8ac49273c0b5 to your computer and use it in GitHub Desktop.
Eular and Quaternion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ToQuaternion(yaw, pitch, roll) // yaw (Z), pitch (Y), roll (X) | |
{ | |
// Abbreviations for the various angular functions | |
let cy = Math.cos(yaw * 0.5); | |
let sy = Math.sin(yaw * 0.5); | |
let cp = Math.cos(pitch * 0.5); | |
let sp = Math.sin(pitch * 0.5); | |
let cr = Math.cos(roll * 0.5); | |
let sr = Math.sin(roll * 0.5); | |
let q = {}; | |
q.w = cr * cp * cy + sr * sp * sy; | |
q.x = sr * cp * cy - cr * sp * sy; | |
q.y = cr * sp * cy + sr * cp * sy; | |
q.z = cr * cp * sy - sr * sp * cy; | |
return q; | |
} | |
function ToEulerAngles(q) { | |
let angles = {}; | |
// roll (x-axis rotation) | |
let sinr_cosp = 2 * (q.w * q.x + q.y * q.z); | |
let cosr_cosp = 1 - 2 * (q.x * q.x + q.y * q.y); | |
angles.roll = Math.atan2(sinr_cosp, cosr_cosp); | |
// pitch (y-axis rotation) | |
let sinp = 2 * (q.w * q.y - q.z * q.x); | |
if (Math.abs(sinp) >= 1) { | |
angles.pitch = sinp>0 ? Math.PI/2 : -Math.PI/2; // use 90 degrees if out of range | |
} | |
else { | |
angles.pitch = Math.asin(sinp); | |
} | |
// yaw (z-axis rotation) | |
let siny_cosp = 2 * (q.w * q.z + q.x * q.y); | |
let cosy_cosp = 1 - 2 * (q.y * q.y + q.z * q.z); | |
angles.yaw = Math.atan2(siny_cosp, cosy_cosp); | |
return angles; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment