c# - How to compute the angles between 2 vectors, to proceed to a rotation? -
i have 2 vectors same origin, , rotate 1 match other. however, can't find math able compute x angle, y angle , z angle (world coordinates) between two. work angles in local coordinates, don't know if helps rotation around forward vector (local y) can doesn't matter. need object facing right direction.
how ?
there many ways approach this. let me first suggest cross product, easier understand alternatives (like quaternions) , might point in right direction.
basically cross product between 2 vectors (a
, b
) results in third vector (c
)which perpendicular both. interesting note, length of third vector length(a)*length(b)*sin(theta)
, theta angle between a
, b
.
here 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 simple formula.
now trick is, normalize a
, b
. means set length 1. done taking vector , dividing each component 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 input cross product result in c
's length being 1 * 1 * sin(theta)
or sin(theta)
.
(as alternative, can dot product, dmitry bychenko pointed out in comments)
what can next? can freely rotate either a
or b
around vector c
using rotation matrix. note however, need normalize c
again this.
Comments
Post a Comment