Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Quaternion
- {
- public:
- float x, y, z, w;
- void Multiply(const Quaternion& other)
- {
- x = x * other.w + y * other.z - z * other.y + w * other.x;
- y = -x * other.z + y * other.w + z * other.x + w * other.y;
- z = x * other.y - y * other.x + z * other.w + w * other.z;
- w = -x * other.x - y * other.y - z * other.z + w * other.w;
- }
- Vector3 GetForwardVector()
- {
- return Vector3(
- 2 * (x * z + w * y),
- 2 * (y * z + w * x),
- 1 - 2 * (x * x + y * y)
- );
- }
- static Vector3 ToEulerAngles(const Quaternion& q)
- {
- Vector3 v;
- // roll (x-axis rotation)
- double sinr_cosp = + 2.0 * (q.w * q.x + q.y * q.z);
- double cosr_cosp = + 1.0 - 2.0 * (q.x * q.x + q.y * q.y);
- v.Z = (float)atan2(sinr_cosp, cosr_cosp);
- // pitch (y-axis rotation)
- double sinp = +2.0 * (q.w * q.y - q.z * q.x);
- if (sinp >= 1 || sinp <= -1)
- v.Y = (float)copysign(Math.PI / 2, sinp); // use 90 degrees if out of range
- else
- v.Y = (float)asin(sinp);
- // yaw (z-axis rotation)
- double siny_cosp = +2.0 * (q.w * q.z + q.x * q.y);
- double cosy_cosp = +1.0 - 2.0 * (q.y * q.y + q.z * q.z);
- v.X = (float)atan2(siny_cosp, cosy_cosp);
- return v;
- }
- static Quaternion CreateFromAxisAngle(const Vector3& vector, float angle)
- {
- Quaternion q;
- float s = sin(angle / 2);
- q.x = vector.x * s;
- q.y = vector.y * s;
- q.z = vector.z * s;
- q.w = cos(angle / 2);
- return q;
- }
- static Quaternion CreateFromYawPitchRoll(double yaw, double pitch, double roll) // yaw (Z), pitch (Y), roll (X)
- {
- // Abbreviations for the various angular functions
- double cy = cos(yaw * 0.5);
- double sy = sin(yaw * 0.5);
- double cp = cos(pitch * 0.5);
- double sp = sin(pitch * 0.5);
- double cr = cos(roll * 0.5);
- double sr = sin(roll * 0.5);
- Quaternion q;
- q.w = (float)(cy * cp * cr + sy * sp * sr);
- q.x = (float)(cy * cp * sr - sy * sp * cr);
- q.y = (float)(sy * cp * sr + cy * sp * cr);
- q.z = (float)(sy * cp * cr - cy * sp * sr);
- return q;
- }
- Quaternion(float x, float y, float z, float w)
- {
- this->x = x;
- this->y = y;
- this->z = z;
- this->w = w;
- }
- Quaternion() = default;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement