Quaternions Mar 22, 2006
And now the last of my 3d math C++ classes. In the simplest terms, quaternions consist of 4 values(x, y, z, w), and are useful in storing and manipulating rotations or orientations. I've also written a quaternion math article where I attempt to describe the common operations and how quaternions work in more detail.
When I created my original character animator many years ago, I used only Euler angles for joint rotations. I soon found out this wasn't a great idea, because depending on order of transformations, rotating around an axis would produce different results. Likewise interpolation between rotations wouldn't always follow the direct path. So I discarded Euler angles in favor of using quaternions. It wasn't long until I added Euler angles back in, but only as an option for certain joint types. I use an angle for a 1 axis hinge joint, and sometimes for other joints that don't have a very full 3D rotation range, like neck or eyes. This is because angle values can be easier to graph and easier to use a wide variety of interpolation methods with. C++ Quaternion Class
What functions are needed in a quaternion class?You need to be able to create a quaternion from an axis and angle. Also, like with matrices, I use the multiplication operator to concatenate quaternion rotations. I have an invert function to invert the rotation. There's a slerp function, to create a quaternion from spherical linear interpolation of two other quaternions. Finally, at some point you'll probably want to convert quaternions to matrices, so there's a To Matrix function. (Actually I prefer using a From Quat function and constructor in the Matrix class, but since I put the Matrix class up first, I did it this way. ) Using the Quaternion Class
I couldn't think of a simple useful example, so here's one that's simple but not so useful. It will rotate a point P1 between two defined rotations. t is the 0-1 interpolation value.
CVec3 RotatePoint( float t, CVec3 P1 ) { CQuat QRot; CQuat Q1( 90.0f, CVec3(0, 1, 0) ); // Set by axis-angle CQuat Q2( 45.0f, CVec3(0, 0, 1) ); QRot.Slerp( Q1, Q2, t ); CMatrix M; QRot.ToMatrix( M.mf ); return M * P1; } Download Code
quat.h : Partially based on my C++ quaternion class. As usual, I hope I didn't mess it up. You should read over the code to get an idea of how to use the functions. You need to include math.h before this class since it uses the sin & cos functions.
|