user5670402
user5670402

Reputation:

Change color of one face of the cube - THREE.js

I am learning OOP while using Three.js. I know, a hard way to do it. So i created a box in the scene. Now i want to change color of one face of that cube.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 100, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.position.set(5, 5, 10);

var geo = new THREE.BoxGeometry(5,2,5);
var mat = new THREE.MeshBasicMaterial({color:0xff0ff0, side:THREE.DoubleSide});

var mesh = new THREE.Mesh( geo, mat);
scene.add(mesh);

//Right there i want to chance color of the face. Its not working
mesh.geometry.faces[5].color.setHex( 0xffffff ); 

var edge = new THREE.WireframeHelper( mesh, 0x00ff00 );
scene.add(edge);

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
renderer.render(scene, camera);

EDIT: the reason it did not work for me was the color i used 0xffffff. This program will work unless color is 0xffffff.

Upvotes: 3

Views: 5338

Answers (1)

WestLangley
WestLangley

Reputation: 104763

In your case, if you want to change the color of one face of the cube, you will need to specify vertexColors in your material.

var geo = new THREE.BoxGeometry( 5, 2, 5 );

var mat = new THREE.MeshBasicMaterial( { color:0xff0ff0, vertexColors: THREE.FaceColors } );

var mesh = new THREE.Mesh( geo, mat );

mesh.geometry.faces[ 5 ].color.setHex( 0x00ffff ); 

The rendered face color will be the specified face color tinted by the material color.

If you change a face color after the mesh has been rendered at least once, you will have to set:

mesh.geometry.colorsNeedUpdate = true;

three.js r.80

Upvotes: 4

Related Questions