Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find rotation matrix between two vectors in THREE.js

I'm looking for the way to find rotation matrix between two defined vectors in THREE.js.

For Example

v1 = new THREE.Vector3(1, 1, 1) v2 = new THREE.Vector3(1, 1, -1)

I need this rotation matrix to rotate whole object in next step.

like image 443
kriskodzi Avatar asked Aug 08 '14 08:08

kriskodzi


People also ask

How do I find the rotation between 2 vectors?

First step, you want to find the angle between the two vectors using the dot product. Next, to find the axis of rotation, use the cross product. Knowing that the cross product will yield a vector perpendicular to both u and v , crossing them in either order will give an appropriate axis.

How do you find the angle between two vectors in three Js?

You can just calculate the angle between two vectors via Vector3. angleTo().

What is 3x3 rotation matrix?

described as a counterclockwise rotation by an angle θ about the z-axis. The matrix. representation of this three-dimensional rotation is given by the real 3 × 3 special. orthogonal matrix, R(z,θ) ≡ 


2 Answers

You can define a rotation from two unit-length vectors v1 and v2 like so:

var quaternion = new THREE.Quaternion(); // create one and reuse it

quaternion.setFromUnitVectors( v1, v2 );

In your case, you need to normalize your vectors first.

You can then apply that rotation to an object using the following pattern:

var matrix = new THREE.Matrix4(); // create one and reuse it

matrix.makeRotationFromQuaternion( quaternion );

object.applyMatrix( matrix );

Alternatively, if you do not require the matrix, you can just apply the quaternion directly:

object.applyQuaternion( quaternion );

three.js r.86

like image 58
WestLangley Avatar answered Nov 16 '22 02:11

WestLangley


I don use quaternions instead I would do it like this (do not use THREE.js. either):

construct 4x4 transform matrix for first vector V1 (V1,V2 lays on its XY plane and V1 is X axis)

double V1[3],V2[3]; // input
double X[3],Y[3],Z[3],P[3]; // output
double m[16]; // OpenGL like transform matrix
X = V1;
Z = V1 x V2;
Y = X x Z;
X/=|X|;
Y/=|Y|;
Z/=|Z|;
P = (0,0,0);
m[ 0]=X[0];
m[ 1]=X[1];
m[ 2]=X[2];
m[ 3]=0;
m[ 4]=Y[0];
m[ 5]=Y[1];
m[ 6]=Y[2];
m[ 7]=0;
m[ 8]=Z[0];
m[ 9]=Z[1];
m[10]=Z[2];
m[11]=0;
m[12]=P[0];
m[13]=P[1];
m[14]=P[2];
m[15]=1;

now apply rotation transform matrix around Z axis on it

double angle = acos( (V1.v2)/(|V1|.|V2|) )
  • rotate around Z axis by +/- angle
  • the angle sign depends on the Y axis cross product operands order
  • not sure right now from the head but you will see
  • if you set it wrong the V2 will be on opposite side
like image 41
Spektre Avatar answered Nov 16 '22 03:11

Spektre