While working with Three.js, I encountered an issue where the mesh I was trying to rotate using keyboard controls was not behaving as expected. Regardless of the axis I rotated around, the mesh did not rotate in the intended direction.
Specifically, when rotating the mesh around one axis (Y), it did not rotate around another axis (X) as anticipated.
The code snippet used for rotating the cube is shown below: mesh.rotation.x += 0.03;
var camera, scene, renderer, mesh;
init();
animate();
function init() {
// Setting up the camera
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
camera.position.set( 1, 2, - 2 );
// Setting up the scene
scene = new THREE.Scene();
camera.lookAt( scene.position );
// Cube Setup
var geometry = new THREE.BoxBufferGeometry( 0.5, 0.5, 0.5 );
var material = new THREE.MeshNormalMaterial();
mesh = new THREE.Mesh( geometry, material );
mesh.position.set(0.5,0.5,0.5);
mesh.rotation.y = 0.5;
scene.add( mesh );
// Adding grid and axes
scene.add( new THREE.GridHelper( 4, 10 ) );
scene.add( new THREE.AxesHelper() );
// Adding renderer
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
}
function animate() {
requestAnimationFrame( animate );
// The cube does not rotate around its local x-axis
mesh.rotation.x += 0.03;
renderer.render( scene, camera );
}
body {
margin: 0;
}
<script src="//cdn.rawgit.com/mrdoob/three.js/master/build/three.min.js"></script>
To troubleshoot the issue, I attempted the following:
- I came across this question discussing global rotation versus local rotation, but the solutions involved using
THREE.Group()
, which I wasn't utilizing. - I found this question about combining global and local rotation, but the suggestions relied on rotation matrices, which I was not employing.
- I read through this question on using the
Object3D.rotateOnAxis()
method. Unfortunately, this approach didn't work for my scenario as it always created an axis from the origin to the position of my mesh. I needed to both rotate and translate my mesh to different positions.