Find rotation angle to align vector with other vector

39 Views Asked by At

First of all, sorry if anything is unclear or this is a dumb question, but I've been working on this a bit too long and can't find a solution.

I have two vectors pointing in different directions: Vector A and vector B. My goal is to rotate A so that it matches the direction of B, and I want to apply that rotation with an angle. A and B are Vector3, but they both have a z component of 0.

I tried using $\operatorname{acos}(\frac{A\cdot B}{\|A\| \|B\|})$, and that does give me a correct angle, but the sign is not always right. It gives me the same angle when B is 45° to the right of A as when B is 45° to the left of A.

1

There are 1 best solutions below

0
On

An alternative is to set up the matrix transformation for the rotation (from A to B).
$$\begin{bmatrix} \cos(\theta) & -\sin(\theta)\\ \sin(\theta) & \cos(\theta) \end{bmatrix} \begin{bmatrix} a_1\\ a_2 \end{bmatrix} = \begin{bmatrix} b_1\\ b_2 \end{bmatrix}.$$ We can re-write the inverse equations -- for going from components and solving for angles: $$\begin{bmatrix} a_1 & -a_2\\ a_1 & a_2 \end{bmatrix} \begin{bmatrix} \cos(\theta)\\ \sin(\theta) \end{bmatrix} = \begin{bmatrix} b_1\\ b_2 \end{bmatrix}.$$ If you solve this system, you will find unique values for $\cos(\theta)$ and $\sin(\theta)$, which you can solve to give you unique angle.

The cosine alone is not enough to give the correct sign.