I recently had to solve the problem of extracting rotations around individual axes in 3D space for arbitrary rotations represented as quaternions.  I’ve seen a lot of people around forums and so on having problems with this, same as me, but not really getting any satisfying answers, so I thought I would share my approach to the problem here.

But first a rant, hah! Converting from quaternions to Euler angles is often fine, however when approaching certain orientations the values on some axes seem to unexpectedly flip 180 degrees. It turns out that the same quaternion has two valid Euler representations with one of them being the one you would expect and the other being flipped 180 degrees on two axes, and I haven’t been able to find a reliable method of determining which is the appropriate set of Euler angles for my purpose and any other possible solution I have looked into has had similar problems.

I would have expected this to be the sort of problem that is dealt with and solved quite routinely, so if I missed something or did something wrong I would certainly like to know!

Also, suggestions to simply store and handle your rotations as Euler angles are not very useful when, for example, you are relying on a physics engine to produce your rotations, not to mention that being able do calculations using quaternions is quite essential in general!

In any case, I came up with this geo-trigonometric method of extracting some angles that was useful for my case, perhaps they could be for others as well? It all boils down to the following method:

Using it I was able to deconstruct my quaternion orientations axis for axis and get some fairly reliable results. The method computes the intersecting line between two planes and then the angle-axis rotation that would take the supplied vector vb into the line of intersection. So to calculate, for example, the pitch you would pass the right vector as va (the normal of the plane of rotation) and the forward facing vector as vb (the vector to rotate), both in the frame of the quaternion rotation, and lastly, as vn you would supply a normal facing upwards, to represent the horizontal plane. An example of this sort of rotation is seen in the image above, represented by the red arc;

It is always nice to see how to use the code and this sort of thing is probably easier to comprehend by playing around a bit with something interactive, so I put together this small Unity project.