BUZZE - 3 months ago 22

C# Question

I have 2 vectors with the same origin, and I would simply like to rotate one to match the other. However, I just can't find the math to be able to compute the x angle, the y angle and the z angle (World coordinates) between the two.

It would also work to get this angles in Local coordinates, I don't know if it helps but the rotation around the Forward vector (Local Y) can be anything it doesn't matter. I only need my object to be facing the right direction.

How could I do ?

Answer

There are many ways to approach this. Let me first suggest the **cross product**, as it is easier to understand than most alternatives (like Quaternions) and might Point you in the right direction.

Basically the cross product between two vectors (`a`

and `b`

) results in a third vector (`c`

)which is perpendicular to both. It is also interesting to note, that the length of this third vector is exactly `length(a)*length(b)*sin(Theta)`

, where Theta is the angle between `a`

and `b`

.

Here is what it looks like:

```
c.x = a.y * b.z - a.z * b.y
c.y = a.z * b.x - a.x * b.z
c.z = a.x * b.y - a.y * b.x
```

A very simple formula.

Now the trick is, to normalize `a`

and `b`

. Which means to set their length to 1. This is done by taking the vector and dividing each component by it's length

```
length_a = sqrt(a_old.x * a_old.x + a_old.y * a_old.y + a_old.z * a_old.z)
a.x = a_old.x / length_a
a.y = a_old.y / length_a
a.z = a_old.z / length_a
```

Using both normalized vectors as Input for the cross product will result in `c`

's length being `1 * 1 * sin(Theta)`

or just `sin(Theta)`

.

(As an alternative, you can also do this with a **dot product**, as Dmitry Bychenko pointed out in the comments)

What can you do next? You can now freely rotate either `a`

or `b`

around vector `c`

using a Rotation Matrix. Do note however, that you would need to normalize `c`

again to do this.