Skip to content Skip to sidebar Skip to footer

Merging Meshes That Have Different Colors

Using Three.js r75 I am trying to display cubes that change color depending on an integer value from green to red. I have tried multiple ways as I am stuck on this. I was unable to

Solution 1:

You are merging geometries so you can render with a single draw call and a single material, but you want each of the merged geometries to have a different color.

You can achieve that by defining vertexColors (or faceColor) in your geometry. Here is a pattern to follow:

// geometryvar geometry = newTHREE.Geometry();

for ( var count = 0; count < 10; count ++ ) {

    var geo = newTHREE.BoxGeometry( 5, 5, 5 );

    geo.translate( THREE.Math.randFloat( - 5, 5 ), THREE.Math.randFloat( - 5, 5 ), THREE.Math.randFloat( - 5, 5 ) );

    var color = newTHREE.Color().setHSL( Math.random(), 0.5, 0.5 );

    for ( var i = 0; i < geo.faces.length; i ++ ) {

        var face = geo.faces[ i ];
        face.vertexColors.push( color, color, color ); // all the same in this case//face.color.set( color ); // this works, too; use one or the other

    }

    geometry.merge( geo );

}

Then, when you specify the material for the merged geometry, set vertexColors like so:

// materialvar material = new THREE.MeshPhongMaterial( {
    color: 0xffffff, 
    vertexColors: THREE.VertexColors // or THREE.FaceColors, if defined
} );

Your geometry will be rendered with a single draw call. You can verify that by typing renderer.info into the console. renderer.info.render.calls should be 1.

three.js r.75

Solution 2:

cubeMat.material.color.setRGB won't work because it's like you're calling the material twice (cubeMat and material), try this instead:

cube.material.color.setRGB( value, value, value );

Solution 3:

Turns out if you merge the geometry the materials cant have different colors. I had to set the face color of each cube before merging.

See

Changing material color on a merged mesh with three js

Three js materials of different colors are showing up as one color

Post a Comment for "Merging Meshes That Have Different Colors"