I am new to three.js, and in a program I am creating, I would like to make different colors for different sides of the cube. The arrow keys control cube rotation. For example, could I have red on one facet, orange on another, yellow on another, green on another, blue on another, and purple on the last?
Here is the javascript code I have so far:
var scene, camera, renderer, cube;
var rotateSpeed = 0.1; // initial rotation speed
var cubeRotation = { x: 0, y: 0, z: 0 };
function createCube() {
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var cubeMaterial = new THREE.MeshBasicMaterial({ color: 0x00ffff })
cube = new THREE.Mesh(geometry, cubeMaterial);
scene.add(cube);
}
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
createCube();
}
function animate() {
requestAnimationFrame(animate);
// Update cube rotation based on arrow key input
cube.rotation.x = cubeRotation.x;
cube.rotation.y = cubeRotation.y;
cube.rotation.z = cubeRotation.z;
renderer.render(scene, camera);
}
// Function to handle key presses (arrow keys)
function onKeyDown(event) {
switch(event.keyCode) {
case 37: // Left arrow
cubeRotation.y -= rotateSpeed;
break;
case 38: // Up arrow
cubeRotation.x -= rotateSpeed;
break;
case 39: // Right arrow
cubeRotation.y += rotateSpeed;
break;
case 40: // Down arrow
cubeRotation.x += rotateSpeed;
break;
}
}
// Add event listener for keydown
window.addEventListener('keydown', onKeyDown, false);
// Initialize and animate
init();
animate();