Search code examples
matrixrotationthree.jsnormalseuler-angles

Three.js - Set rotation of object from normalized directions of the X, Y and Z-Axis


From a model file object definition the placement a new object is given by a location (a point in space) and the normalized directions of the X-Axis, the Y-Axis and the Z-Axis.

How can i translate this to a THREE.Euler so i can rotate my object correctly in space.

So the axes are off type THREE.Vector3. If the new object is aligned with the world the values would be:

xAxis = new THREE.Vector3( 1, 0, 0 );

yAxis = new THREE.Vector3( 0, 1, 0 );

zAxis = new THREE.Vector3( 0, 0, 1 );

But if for example the whole local UCS of the object is rotated 180 degrees ( or Math.PI ) around the zAxis they would look like this:

xAxis = new THREE.Vector3( -1, 0, 0 );

yAxis = new THREE.Vector3( 0, -1, 0 );

zAxis = new THREE.Vector3( 0, 0, 1 );

So I need to do something like this:

var object3D = new THREE.Object3D();

object3D.position = location;

var euler = new THREE.Euler();

euler.setFromNormalizedAxes( xAxis, yAxis, zAxis );

object3D.rotation = euler;

Or create a rotation matrix from those axes:

var rotationMatrix = new THREE.Matrix4();

rotationMatrix.setFromNormalizedAxes( xAxis, yAxis, zAxis );

object3D.rotation.setFromRotationMatrix( rotationMatrix, "XYZ" );

I am not so good yet with these rotation matrices and euler rotations...


Solution

  • In the example you gave, the answer would be

    object.quaternion.setFromRotationMatrix(
    
        new THREE.Matrix4( -1,  0,  0,  0,
                            0, -1,  0,  0,
                            0,  0,  1,  0,
                            0,  0,  0,  1 )
    
    );
    

    The columns of the upper 3x3 of the Matrix4 are the new x-, y-, and z-axes.

    You could set object.rotation instead. It does not matter.

    three.js r.66