3D game programmers tend to have a love-hate relationship with quaternions. They provide a fast, accurate way to handle free rotations in three-dimensional space, but they are maddeningly difficult to understand. Having fought with them recently myself, I'm going to try to summarize what I've learned here.

The single most helpful resource to me when implementing quaternion code was the Using Quaternions to Perform 3D Rotations tutorial on CProgramming.com. Unfortunately, there are a few subtle details that this article did not explain very clearly, which I will outline here.

First, the tutorial claims that the four components of a quaternion represent an axis of rotation and a magnitude. If you try to understand quaternions this way, you will go mad. I have never been able to discern anything useful by staring at the component values of a quaternion. Do yourself a favor and convert it to either axis-angle format or a transformation matrix before trying to make sense of a given quaternion by eyeballing it.

Next up, quaternion concatenation. Quaternions are concatenated via multiplication, and quaternion multiplication is not commutative. So, the tutorial claims that to adjust an existing orientation q1 by rotation q2, you should perform the operation q2 * q1. This is correct if you want to perform the rotation q2 relative to the object being rotated. As an example, if you have an airplane oriented with transformation q1, and you want to bank by q2, then that is the correct way to do it. However, if you want to perform the rotation with respect to the global coordinate system, this is the opposite of what you want. Imagine that the airplane mentioned earlier has crashed at orientation q1, and you want to let the player click and drag to rotate the camera around the crashed plane. If the user rotates the scene by q2, then you want to update the plane with q1 * q2. This difference is crucial if you are building an object-manipulation game like Cogs. (Incidentally, judging by the limitations of that particular game, I'm pretty sure it was implemented with Euler angles, not quaternions. A pity.)

Finally, the identity quaternion, a quaternion representing no rotation at all, is useful for initializing things. The above tutorial simply states that the identity quaternion is (1, 0, 0, 0). It's important to note that w--not x--is initialized to 1. It makes a difference!

Now, if you're implementing a game for Android, you're in luck! I have a well-tested Java quaternion implementation ready to go. Just grab Quaternion.java and drop it in your project. Do note that this code makes use of android.util.FloatMath. If you want to use this in a Java project outside of Android, you can cheat and use the class under the test/ directory that wraps java.util.Math.

If you're an independent game dev, I hope you learned something useful and that you'll go create something awesome.