Ramy Al Zuhouri - 1 year ago 172

Javascript Question

I am trying to rotate an object around the world axis. I've found this question: How to rotate a object on axis world three.js?

But it didn't solve the problem by using this function:

`var rotWorldMatrix;`

// Rotate an object around an arbitrary axis in world space

function rotateAroundWorldAxis(object, axis, radians) {

rotWorldMatrix = new THREE.Matrix4();

rotWorldMatrix.makeRotationAxis(axis.normalize(), radians);

rotWorldMatrix.multiplySelf(object.matrix); // pre-multiply

object.matrix = rotWorldMatrix;

object.rotation.getRotationFromMatrix(object.matrix, object.scale);

}

`multiplySelf`

`getRotationFromMatrix`

I tried to use

`Quaternion`

`function mouseUp(event) {`

var x= event.clientX;

var y= event.clientY;

var dx= (x - xBegin);

var dy= (y - yBegin);

var quaternion= new THREE.Quaternion();

quaternion.setFromAxisAngle(new THREE.Quaternion(dy,dx,0).normalize(),Math.sqrt(dx*dx+dy*dy)/250.0);

object.quaternion.multiplyQuaternions(quaternion,object.quaternion);

}

It rotates correctly as long as the object is in vertical or horizontal position, but if it's for example at 45 degrees from the x axis, it rotates very slowly and in the opposite direction of the click.

Answer

As long as the object does not have a rotated parent, you can rotate the object around a *World* axis like so:

```
var q = new THREE.Quaternion(); // create once and reuse
q.setFromAxisAngle( axis, angle ); // axis must be normalized, angle in radians
object.quaternion.premultiply( q );
```

three.js r.78

Source (Stackoverflow)