Skip to content
Advertisement

What’s the right way to rotate an object around a point in three.js?

Most tutorials/questions about three.js suggest the way to rotate an object around a point using three.js is to create a parent object at the position you want to rotate around, attach your object, and then move the child. Then when the parent is rotated the child rotates around the point. Eg;

//Make a pivot
var pivot = new THREE.Object3D();
//Make an object
var object = new THREE.Mesh( new THREE.BoxGeometry(2,2,2), new THREE.MeshBasicMaterial() );
//Add object to pivot
pivot.add(object);

//Move object away from pivot
object.position.set(new THREE.Vector3(5,0,0));

//rotate the object 90 degrees around pivot
pivot.rotation.y = Math.PI / 2;

This works but it’s incredibly limiting – if you want to rotate an object around a different point you can’t because an object can’t have two parents.

The next method that works is applying a rotated matrix to the object’s position, e.g.;

//Make an object
var object = new THREE.Mesh( new THREE.BoxGeometry(2,2,2), new THREE.MeshBasicMaterial() );
//Move the object
object.position.set(new THREE.Vector3(5,0,0);

//Create a matrix
var matrix = new THREE.Matrix4();
//Rotate the matrix
matrix.makeRotationY(Math.PI / 2);

//rotate the object using the matrix
object.position.applyMatrix4(matrix);

Again, this works, but there doesn’t appear to be a way to set the point of rotation. It’s always the origin of the world.

Another option is a utility method in sceneUtils to detach a child from a parent object and another method to attach a new parent, but the documentation for that warns against using it, and it’s never used in any example code.

Ultimately I want to be able to make a cube follow an S shaped path, but without this (seemingly) basic thing I’m finding it rather difficult.

tl;dr I want to rotate a three.js object around a series of different points. What would be a good way to approach that?

Advertisement

Answer

This answer might help: Three JS Pivot point

There are several ways to approach this problem. As you mentioned, you CAN swap the pivot point in the parenting approach, but it’s a lot of work, converting the object position to/from the different coordinate systems.

Instead, you can always look at it this way (pseudo-code):

  1. Move the object to the pivot point

    1.1. SUBTRACT the the pivot point from your object’s original position

  2. Apply your rotation

  3. Move the object BACK by the same position vector

    1.1. ADD the the pivot point to your object’s new position

Note: Everything is in world coordinates, so you may need to convert appropriately.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement