javascriptthree.jstexturingonmouseclick

Changing the color of every face of a cube


I've been trying to change the color of my cube when it is clicked on. The problem I'm having is that it doesn't seem to work when I use a MeshFaceMaterial. So far I have managed to change the color of a single face of the cube like this:

if ( intersects.length > 0 )
{
    console.log("Hit @ " + toString( intersects[0].point ) );
    // change the color of the closest face.
    intersects[ 0 ].face.color.setRGB( 0.8 * Math.random() + 0.2, 0, 0 ); 
    intersects[ 0 ].object.geometry.colorsNeedUpdate = true;
}

How do I now change my code so that ALL of the faces change color when one face is clicked? Thanks!


Solution

  • Get the list of all faces from the geometry property:

    if ( intersects.length > 0 )
    {
        console.log("Hit @ " + toString( intersects[0].point ) );
        // change the color of the closest face.
        var faces = intersects[0].object.geometry.faces;
        for (var i = 0; i < faces.length; i++) {
           faces[i].color.setRGB( 0.8 * Math.random() + 0.2, 0, 0 ); 
        }
    
        intersects[ 0 ].object.geometry.colorsNeedUpdate = true;
    }