I'm trying to change the color of a cube in three.js to a random color. I've looked at various resources, like Changing color of cube in three.js, but for some reason, my code doesn't update the cube's color despite the console output showing the correct values. However, manually setting the color using
cube.material.color.setRGB(100, 0, 0);
works! What could be going wrong?
var r = 1;
var g = 1;
var b = 1;
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var geometry = new THREE.CubeGeometry(1, 1, 1);
var material = new THREE.MeshPhongMaterial();
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
var directionalLight = new THREE.DirectionalLight('white', 1);
directionalLight.position.set(1, 0, 1);
scene.add(directionalLight);
camera.position.z = 5;
r = Math.round(Math.random() * (255 - 0) + 0);
g = Math.round(Math.random() * (255 - 0) + 0);
b = Math.round(Math.random() * (255 - 0) + 0);
/* The console output below is correct, but there seems to be an issue with setting the color. Manually inputting the color values does work! */
console.log(r, g, b);
cube.material.color.setRGB(r, g, b);
function render() {
requestAnimationFrame(render);
renderer.render(scene, camera);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
//cube.position.z += 0.01;
}
render();