Showcase and discover digital art at yex

Follow Design Stacks

Subscribe to our free newsletter to get all our latest tutorials and articles delivered directly to your inbox!

Doing Quaternion Math

Doing Quaternion Math

If you’ve spent any time looking for ways to create 3D objects or scenes you’ve probably encountered quaternions at one point or another. Quaternions are four-dimensional objects that use w, x, y, and z components to describe an axis of rotation and an angle. Quaternions are often used in 3D engines to rotate points in space quickly. Because quaternions contain only four variables, they require less memory and fewer calculations when compared to 3D matrix methods. This makes them ideal for scripting languages like ActionScript.

Without going into the gory details behind the mathematics of quaternions, where they came from, and why they work the way they do, I present a few simple equations that you can use to construct quaternions:

ca = Math.cos(angle/2);
sa = Math.sin(angle/2);
m = Math.sqrt(x*x + y*y + z*z);
Qx = a/m * sa;
Qy = b/m * sa;
Qz = c/m * sa;
Qw = ca;

In the equations above, the variables x, y, and z are the x, y, and z components of the axis of rotation, angle is the angle in radians, and Qx, Qy, Qz, and Qw are the components of the resulting quaternion. As it turns out, these are the exact equations that we will use later in the Quaternion class.

An important feature of quaternions is that you can multiply, or concatenate, them together to create a composite quaternion that is a combination of the two axes and rotations defined by each. Whenever you require multiple rotations, concatenation saves processing time by eliminating the need to rotate each point separately by each quaternion. The equations for concatenating quaternions are also quite simple:

Q2*Q1 = Q1w*Q2w – Q1x*Q2x – Q1y*Q2y – Q1z*Q2z,
Q1w*Q2x + Q1x*Q2w + Q1y*Q2z – Q1z*Q2y,
Q1w*Q2y + Q1y*Q2w + Q1z*Q2x – Q1x*Q2z,
Q1w*Q2z + Q1z*Q2w + Q1x*Q2y – Q1y*Q2x

Another important feature of Quaternions is that you can convert 3D points into quaternion notation simply by setting the x, y, and z components of the quaternion to be the x, y, and z components of the point and by setting the w component to zero. After you convert a point you can multiply it by a quaternion to rotate the point in space. When you write the Quaternion and Node classes in the next section, you will see how this is done in code.