Skip to content

Instantly share code, notes, and snippets.

@TheAllenChou
Last active August 5, 2019 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheAllenChou/5a9a255dccc106c39f5eda38cb0e2d02 to your computer and use it in GitHub Desktop.
Save TheAllenChou/5a9a255dccc106c39f5eda38cb0e2d02 to your computer and use it in GitHub Desktop.
Conversion between Quaternions & Angular (Axis-Angle) Vectors
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