Working With Quaternions in Maya With Python and OpenMaya

Quaternions are a very effective way of setting orientations or performing rotations, but if you want to do that using Python, you’re going to need to leverage the OpenMaya API.
Euler or Quaternions?#
Most of the time, when working with rotations in Maya, you’re going to be working with Euler (pronounced oiler) angles. They’re intuitive to work with, allow for rotations greater than 360 degrees, and provide greater interpolation control between keyframes because of the ability to manipulate keyframe tangents.
Sometimes, you’ll need to use quaternions though. Especially when exporting out of Maya to other applications that prefer quaternions or working with other APIs. Quaterions have their benefits too. Quaternions allow for smooth rotations from one orientation to another using the shortest rotation. Thus, they don’t suffer from gimbal locking or flipping.
Getting to Work#
To work with quaternions in Maya using Python, you’ll need to use the
OpenMaya API. Most of the work is done with MFnTransform
and
MQuaternion
. Let’s start out by getting a quaternion that represents
a transform node’s current orientation:
Setting a Transform’s Orientation Using Quaternions#
If you want to set the orientation of a transform node using a
quaternion, you can use MFnTransform.setRotation
or
MFnTransform.setRotationComponents
. The former takes an
MQuaternion
object as a parameter and the latter can take sequence
of numbers representing x, y, z, w:
Relative Rotations Using Quaternions#
If you want to perform a relative rotation instead of a complete
orientation update, you can use MFnTransform.rotateBy
:
Lastly, quaternions can be used to interpolate between two rotations
using a technique called, Spherical Linear Interpolation (slerp) and the
Maya Python API provides a simple function to accomplish that,
MQuaternion.slerp
.
You can take slerp a step further to animate the rotation.