Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Given two vectors, a direction and an up: how do I construct a quaternion so that when a coordinate system is transformed by it, it's X-axis points in the original direction vector?

share|cite|improve this question
Quaternions encode rotation matrix, thus find the rotation matrix needed, and transcribe it into quaternion representation. – Sasha Aug 29 '11 at 13:17
up vote 4 down vote accepted

You can construct a quaternion to rotate a given normalized vector $\mathbf{v}$ onto a normalized vector $\mathbf{w}$ by taking the axis from the cross product and the angle from the dot product

$\mathbf{a}=\mathbf{v}\times\mathbf{w},\quad\quad\quad \theta = \arccos(\mathbf{v}\cdot\mathbf{w})$

and of course the usual axis-angle to quaternion conversion

$\mathbf{q}=(\cos\frac{\theta}{2}, \mathbf{a}\sin\frac{\theta}{2})$

But be aware that this rotates along the shortest path and therefore need not keep the up vector of your object. If you want to rotate around the normalized up-axis $\mathbf{u}$, then this is of course the rotation axis. But then you have to compute the angle in the plane perpendicular to the up-axis, so you first need to project the source and target vectors into this plane before taking their dot product, by using

$\mathbf{v}=\mathbf{v}-(\mathbf{v}\cdot\mathbf{u})\mathbf{u},\quad\quad\quad \mathbf{v}=\frac{\mathbf{v}}{\|\mathbf{v}\|}$

and the same for $\mathbf{w}$. Then you can compute the rotation as above.

share|cite|improve this answer
Thanks! This is a whole lot simpler than I expected. – Hannesh Aug 29 '11 at 21:13

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.