Quaternion: FromToRotation Explained

Unity uses the Quaternion class to represent and work with angles. The math behind Quaternions can be confusing, but luckily you rarely have to work with the underlying numbers, and most tasks can be accomplished using the API’s provided. Unfortunately those API’s aren’t always as straight forward as we’d like. In this post I’m going to give a brief explanation of how the FromToRotation method works in the Quaternion class.

The Quaternion.FromToRotation method is a static method that returns a Quaternion that is the angle between two vectors: fromDirection and toDirection. Each vector’s value is specified in world space.

The key to proper use of this method is to remember the vectors fromDirection and toDirection are not just points in space, but represent lines that begin at the origin and end at their specified coordinates.  The rotation that is returned represents the angle between those two lines.

The following diagram is a top down view so we are viewing the XZ plane.  The Quaternion created using the two points in the diagram would result in a rotation approximately 90 degrees around the Y axis (0, 90, 0), which is denoted by the green arc.

The next diagram shows the rotation created using the exact same two points, but in this instance we swapped the order in which the points were specified.

The Quaternion created using the two points in the diagram would result in a rotation approximately 270 degrees around the Y axis (0, 270, 0).

If either vector is at the origin, then the resulting rotation will always be 0.  The reason for this is clear as long as you remember that each vector represents a line from the origin to the specified point in space. Since there is only one line, there can not be an angle separating the two.

About the author