# Quaternion for an object that to point in a direction

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?

-
Quaternions encode rotation matrix, thus find the rotation matrix needed, and transcribe it into quaternion representation. –  Sasha Aug 29 '11 at 13:17

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.

-
Thanks! This is a whole lot simpler than I expected. –  Hannesh Aug 29 '11 at 21:13