I am using threejs to render a cube. Currently I achieved a rotating cube with different textures. Now I am trying to make the cube to rotate using the mouse. In my case now, the cube is rotating:
function animate() {
mesh.rotation.x += .015;
mesh.rotation.y += .015;
mesh.rotation.y += .015;
render();
requestAnimationFrame( animate );
}
Now I have two options:
- I rotate the camera while moving and holding the mouse
- I rotate the cube whilte holding/moving the mouse.
I am also aiming to have two states. One, in which the cube is rotating automatically and one, in which the cube rotates by draging the mouse. I tried already OrbitControler, but it didn't work out. Is there any simple solution to just have a floating rotating cube using the mouse?
My code:
THREE.JS
var camera;
var scene;
var renderer;
var mesh;
var geometry;
var material1;
var material2;
var material3;
var material4;
var material5;
var material6;
var materials;
var meshFaceMaterial;
init();
animate();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 1000);
var light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 0, 1, 1 ).normalize();
scene.add(light);
geometry = new THREE.CubeGeometry( 10, 10, 10);
material1 = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture('img/cub1.jpg') } );
material2 = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture('img/cub2.jpg') } );
material3 = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture('img/cub3.jpg') } );
material4 = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture('img/cub4.jpg') } );
material5 = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture('img/cub5.jpg') } );
material6 = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture('img/cub6.jpg') } );
materials = [material1, material3, material5, material6, material4, material2];
meshFaceMaterial = new THREE.MeshFaceMaterial( materials );
mesh = new THREE.Mesh(geometry, meshFaceMaterial );
mesh.position.z = -50;
scene.add( mesh );
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.getElementById('render').appendChild( renderer.domElement );
window.addEventListener( 'resize', onWindowResize, false );
render();
}
function animate() {
mesh.rotation.x += .015;
mesh.rotation.y += .015;
mesh.rotation.y += .015;
render();
requestAnimationFrame( animate );
}
function render() {
renderer.render( scene, camera );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
render();
}