Last active
August 5, 2019 04:43
-
-
Save TheAllenChou/5a9a255dccc106c39f5eda38cb0e2d02 to your computer and use it in GitHub Desktop.
Conversion between Quaternions & Angular (Axis-Angle) Vectors
This file contains hidden or 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
public static Vector3 GetAxis(Quaternion q) | |
{ | |
Vector3 v = new Vector3(q.x, q.y, q.z); | |
float len = v.magnitude; | |
if (len < MathUtil.Epsilon) | |
return Vector3.left; | |
return v / len; | |
} | |
public static float GetAngle(Quaternion q) | |
{ | |
return 2.0f * Mathf.Acos(Mathf.Clamp(q.w, -1.0f, 1.0f)); | |
} | |
public static Quaternion FromAngularVector(Vector3 v) | |
{ | |
float len = v.magnitude; | |
if (len < MathUtil.Epsilon) | |
return Quaternion.identity; | |
v /= len; | |
float h = 0.5f * len; | |
float s = Mathf.Sin(h); | |
float c = Mathf.Cos(h); | |
return new Quaternion(s * v.x, s * v.y, s * v.z, c); | |
} | |
public static Vector3 ToAngularVector(Quaternion q) | |
{ | |
Vector3 axis = GetAxis(q); | |
float angle = GetAngle(q); | |
return angle * axis; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment