Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davidfoster/cb1b6836b4c88d65a4f5d01566358fc1 to your computer and use it in GitHub Desktop.
Save davidfoster/cb1b6836b4c88d65a4f5d01566358fc1 to your computer and use it in GitHub Desktop.
Normalise a Quaternion
public static class QuaternionExtensions {
//-----------------------------------------------------------------------------------------
// Public Methods:
//-----------------------------------------------------------------------------------------
/// <summary>Returns a <c>Quaternion</c> with the same orientation but with a magnitude of 1.</summary>
public static Quaternion Normalise(this Quaternion self) {
// work out the magnitude, and if it's too small, return identity.
float magnitude = Mathf.Sqrt(Quaternion.Dot(self, self));
// ReSharper disable once ConvertIfStatementToReturnStatement
if (magnitude < Mathf.Epsilon) return Quaternion.identity;
return new Quaternion(self.x / magnitude, self.y / magnitude, self.z / magnitude, self.w / magnitude);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment