Created
March 11, 2021 07:20
-
-
Save akamilkhan/3bcc593aef2049a8414fa3c4c3ca44d9 to your computer and use it in GitHub Desktop.
Quaternion to Euler Angles conversion snippet
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
#include <math.h> | |
struct Quaternion | |
{ | |
double w, x, y, z; | |
}; | |
struct EulerAngles | |
{ | |
double roll, pitch, yaw; | |
}; | |
struct EulerAngles ToEulerAngles(struct Quaternion q) | |
{ | |
struct EulerAngles angles; | |
// roll (x-axis rotation) | |
double sinr_cosp = 2 * (q.w * q.x + q.y * q.z); | |
double cosr_cosp = 1 - 2 * (q.x * q.x + q.y * q.y); | |
angles.roll = atan2(sinr_cosp, cosr_cosp); | |
// pitch (y-axis rotation) | |
double sinp = 2 * (q.w * q.y - q.z * q.x); | |
if (fabs(sinp) >= 1) | |
angles.pitch = copysign(M_PI / 2, sinp); // use 90 degrees if out of range | |
else | |
angles.pitch = asin(sinp); | |
// yaw (z-axis rotation) | |
double siny_cosp = 2 * (q.w * q.z + q.x * q.y); | |
double cosy_cosp = 1 - 2 * (q.y * q.y + q.z * q.z); | |
angles.yaw = 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