How to create a Quaternion rotation from a forward- and up- vector?

2.4k Views Asked by At

I need the rotation Quaternion of an object, I have it's foward and up directions (as 3D vectors), so I thought it would be easy to create a Quaternion rotation from that, but I can't seem to get it right.

I'm sure there are multiple ways to do this. (with or without matrices for example) I just need one that always works.

I'm working in C++, directx, so I have the DirectXMath libraries available to use.

Edit:

Turns out there's an easy way to do this with the directx, as there is a function that creates the TransformationMatrix from forward and upvector.

I'm leaving this open, as I'm still interested in knowing how to do this manually. (withouth directx)

1

There are 1 best solutions below

1
On BEST ANSWER

You calculate “direction-left” vector as $v_{\mathrm{l}}=v_{\mathrm{u}}\times v_{\mathrm{f}}$. Then by writing your vectors as three columns with the order forward—left—up, you obtain a rotation matrix $M$. Finally: $$ q_0= \frac12\sqrt{1 + \mathrm{Tr}\ M},\\ q_1 = \frac{M_{32} - M_{23}}{4q_0},\qquad q_2 = \frac{M_{13} - M_{31}}{4q_0},\qquad q_3 = \frac{M_{21} - M_{12}}{4q_0} $$