Steven Hadley
Steven Hadley

Reputation: 1

Changing colours in three.js, a three js idiosyncrasy?

I am attempting to simply change the colour of a cube in three.js to a random colour, I have searched for and referenced Changing color of cube in three.js, however my code is failing to change the cubes colour even though the console output is correct and setting the colour manually eg(cube.material.color.setRGB(100,0,0);) works! What am I doing 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);


/* issue, the below console output is correct however the colour is not set. Setting the colour values manually works!! */

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();

Upvotes: 0

Views: 428

Answers (1)

WestLangley
WestLangley

Reputation: 104763

When setting a THREE.Color using the setRGB( r, g, b ) method, r, g, and b take values between zero and 1.

color.setRGB( Math.random(), Math.random(), Math.random() );

See http://threejs.org/docs/#api/math/Color.

three.js r.85

Upvotes: 2

Related Questions