Search code examples
mathmatrixvectorthree.js

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.


Solution

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

    const 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:

    const matrix = new THREE.Matrix4(); // create one and reuse it
    
    matrix.makeRotationFromQuaternion( quaternion );
    
    object.applyMatrix4( matrix );
    

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

    object.applyQuaternion( quaternion );
    

    three.js r.152