Skip to content

Instantly share code, notes, and snippets.

@clavis-magna
Created November 24, 2012 04:36
Show Gist options
  • Save clavis-magna/4138387 to your computer and use it in GitHub Desktop.
Save clavis-magna/4138387 to your computer and use it in GitHub Desktop.
local and global rotation functions for THREE.js objects updated for recent revisions of THREE.js
//following two rotation functions are updated versions of code from: https://github.com/mrdoob/three.js/issues/1219
//updated to work in latest versions (r52 tested) of THREE.js
// Rotate an object around an axis in object space
var rotationMatrix
function rotateAroundObjectAxis( object, axis, radians ) {
rotationMatrix = new THREE.Matrix4();
rotationMatrix.makeRotationAxis( axis.normalize(), radians );
object.matrix.multiplySelf( rotationMatrix ); // post-multiply
object.rotation.setEulerFromRotationMatrix(object.matrix, object.order);
}
// Rotate an object around an axis in world space (the axis passes through the object's position)
var rotWorldMatrix;
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.setEulerFromRotationMatrix(object.matrix, object.order);
}
Copy link

ghost commented Apr 25, 2015

Sooo the "axis" argument would be... what?

@jppresents
Copy link

The "axis" argument is a vector of length 1, specifying the axis.

for example x axis: new THREE.Vector3(1, 0, 0);

The bigger problem is, current versions of ThreeJS don't have "setEulerFromRotationMatrix" anymore.
So this doesn't help :(

@nkolban
Copy link

nkolban commented Jun 18, 2016

When I tried this routine, I got the error:

Uncaught TypeError: rotWorldMatrix.multiplySelf is not a function

@zwcloud
Copy link

zwcloud commented Apr 18, 2018

This is quite outdated.

@whatisor
Copy link

whatisor commented May 13, 2018

var rotWorldMatrix = new THREE.Matrix4();
rotWorldMatrix.makeRotationAxis(axis.normalize(), radians);
rotWorldMatrix.multiply(object.matrix);        // post-multiply
object.matrix = rotWorldMatrix;
object.rotation.setFromRotationMatrix(object.matrix,'XYZ');

@jespertheend
Copy link

It seems like this doesn't take the rotation of any parents into account? Just like Object3D.rotateOnWorldAxis()?

@jespertheend
Copy link

jespertheend commented Apr 13, 2020

In case anyone needs this, I managed to solve it like this

let invWorldRot = object.getWorldQuaternion(new THREE.Quaternion()).inverse();
axis.applyQuaternion(invWorldRot);

let deltaLocalRot = new THREE.Quaternion();
deltaLocalRot.setFromAxisAngle(axis, radians);
object.quaternion.multiply(deltaLocalRot);

you need to call object.updateWorldMatrix(true) in order to get up to date results from object.getWorldQuaternion()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment