We will entertain your mind, enhance your brain, expand your lifestyle.


What is Quaternion?

I don’t understand it exactly, so if you want to know more, check out Wikipedia.

Mathematically speaking, it is difficult, but when used in game development, it can be said to be used for rotation processing in three-dimensional space. Unlike rotation using normal three-dimensional coordinate axes (x, y, z) rotation angles (Euler angles), it has the following features.

  • Rotation in three-dimensional space can be easily described, and the amount of calculation is less than that of matrix calculation.
  • Unlike Euler angles, gimbal lock does not occur

Why writing an article?

Since Unity deals with 3D graphics, quaternions are used for internal rotation processing as a matter of course. I wrote “inside”, but in Unity’s editor, the rotation of objects is represented by Euler angles. Euler angles are generally easier to handle when handled by humans

In scripting, it can be process with quaternions, such as rotate by a specified angle. But if we want to determine if a rotating object has reached a certain angle, we want to use Euler angles.

Converting quaternions to Euler angles may give different values than expected. For example, if rotate an object around the X axis by 5 degrees and convert its internal angles (quaternions) to Euler angles, we get:

(x, y, z) =
  (80.0, 0.0, 0.0)
  (85.0, 0.0, 0.0)
  (90.0, 0.0, 0.0)
  (85.0, 180.0, 180.0)
  (80.0, 180.0, 180.0)
  (75.0, 180.0, 180.0)

When it exceeds 90 degrees, unexpected value appears on the y-axis and z-axis. This phenomenon occurs when x-axis is between 90 and 270 degrees. Even if the rotation result of the object is the same, it is different from the expectation, and waiting for (95.0, 0.0, 0.0) is useless. This phenomenon also occurs in the rotation of other axes depending on the combination of values.

Looking at some materials, there is a description that the mutual conversion between quaternions and Euler angles is processed in the order of Z-Y-X axes. Even if it turns out that it cannot be converted uniquely, it cannot be used in actual operation, so we added a process to determine the angle by setting an external counter.

Broom Bridge

As an aside, the inspirational episode of genius is interesting, and the following episode of the Wikipedia article is one of them.

Hamilton walked along the towpath of the Royal Canal with his wife, the concepts behind quaternions were taking shape in his mind. When the answer dawned on him, Hamilton could not resist the urge to carve the formula for the quaternions,
i^2 = j^2 = k^2 = ijk = -1
into the stone of Broom Bridge as he paused on it.