Jayy
Jayy

Reputation: 14808

Coloring individual faces of shape in three.js

I'm extending a simple example which displays a rotating cube, I'd like to change the colour of individual faces, but not having any luck. What's wrong with this code? Thanks

$(function(){
    var camera, scene, renderer,
    geometry, material, mesh;

    init();
    animate();

    function init() {
        scene = new THREE.Scene();
        camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 10000 );
        camera.position.z = 800;

        geometry = new THREE.CubeGeometry( 500, 70, 70 );

        material_1 = new THREE.MeshBasicMaterial( { 
            color: 0xff0000,
            shading: THREE.FlatShading, 
            overdraw: true 
        } );
        material_2 = new THREE.MeshBasicMaterial( { 
            color: 0x00ff00, 
            shading: THREE.FlatShading, 
            overdraw: true 
        } );
        geometry.materials = [material_1, material_2];
        geometry.faces[0].materialIndex = 0;
        geometry.faces[1].materialIndex = 1;
        geometry.faces[2].materialIndex = 0;
        geometry.faces[3].materialIndex = 1;
        geometry.faces[4].materialIndex = 0;
        geometry.faces[5].materialIndex = 1;
        mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial() );

        scene.add( mesh );
        renderer = new THREE.CanvasRenderer();
        renderer.setClearColorHex(0x000000, 1);
        renderer.setSize( window.innerWidth, window.innerHeight );
        document.body.appendChild( renderer.domElement );
    }

    function animate() {
        requestAnimationFrame( animate );
        render();
    }
    function render() {
        mesh.rotation.x += 0.01;
        mesh.rotation.y += 0.05;
        renderer.render( scene, camera );
    }
});

Upvotes: 4

Views: 3352

Answers (1)

skewart
skewart

Reputation: 176

You need to pass an array of materials to the MeshFaceMaterial constructor as an argument.

Instead of:

 mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial() );

You should have:

 mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( geometry.materials ) );

Upvotes: 7

Related Questions