Neil
Neil

Reputation: 8121

Rotate ThreeJS Object3D on a tilted Y axis

I've tried many ways to tilt my object then rotate it on this tilted axis, but no matter what I try it always rotates as though the Y axis is straight up, it doesn't seem to rotate on this new tilted axis, WHY NOT?

this.axis = new Vector3(0, 0, 0.5).normalize()
this.mesh = new Mesh(this.geometry, this.material)
this.mesh.rotateOnAxis(this.axis, Math.degToRad(25))

I've tried using rotateOnWorldAxis, also tried makeRotationAxis on Matrix4 and applying directly to geometry.

Example here:

codesandbox.io

Upvotes: 3

Views: 991

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30390

There are a few ways to achieve this; one solution would be to add additional hierarchy to your scene by introducing a group node. Here the group is added as a child to the scene, and your mesh is added as a child to that group:

this.mesh = new Mesh(this.geometry, this.material);

/* New group */
this.group = new THREE.Group();
/* Tilt group */
this.group.rotateOnAxis(this.axis, Math.degToRad(25));
/* Add mesh to group */
this.group.add( this.mesh );
/* Add group to scene */
this.scene.add( group );

With this added hierarchy, the "axis tilt" is applied to the group instead of to the mesh. In threejs, doing this causes any children (ie mesh) of the group to inherit that tilt as well.

This method provides an intuitive way of combing the tilt with locally applied rotation (ie as you are doing via rotation.y += 0.005) to achieve the desired axis based rotation.

Here's a working codesandbox. Hope that helps!

Alternative method

Alternatively, you could use the rotateY() method to apply a rotation transform around the mesh object's local frame:

this.mesh.rotateY(0.005);

// this.mesh.rotation.y += 0.005 <-- not needed

Here's a working example to demonstrate this approach

Upvotes: 5

Related Questions