Threejs: assign different colors to each vertex in a geometry

前端 未结 3 1593
情书的邮戳
情书的邮戳 2020-12-03 03:09

I want to do picking via IdMapping in Three.js

Because of performance issues I only have one huge geometry, computed like this:

for (var i = 0; i <         


        
3条回答
  •  猫巷女王i
    2020-12-03 04:03

    This code should work for three.js v49, creating an RGB color cube.

    (Related to How to change face color in Three.js)

    // this material causes a mesh to use colors assigned to vertices
    var vertexColorMaterial = new THREE.MeshBasicMaterial( { vertexColors: THREE.VertexColors } );
    
    var color, point, face, numberOfSides, vertexIndex;
    
    // faces are indexed using characters
    var faceIndices = [ 'a', 'b', 'c', 'd' ];
    
    var size = 100;
    var cubeGeometry = new THREE.CubeGeometry( size, size, size );
    
    // first, assign colors to vertices as desired
    for ( var i = 0; i < cubeGeometry.vertices.length; i++ ) 
    {
        point = cubeGeometry.vertices[ i ];
        color = new THREE.Color( 0xffffff );
        color.setRGB( 0.5 + point.x / size, 0.5 + point.y / size, 0.5 + point.z / size );
        cubeGeometry.colors[i] = color; // use this array for convenience
    }
    
    // copy the colors to corresponding positions 
    //     in each face's vertexColors array.
    for ( var i = 0; i < cubeGeometry.faces.length; i++ ) 
    {
        face = cubeGeometry.faces[ i ];
        numberOfSides = ( face instanceof THREE.Face3 ) ? 3 : 4;
        for( var j = 0; j < numberOfSides; j++ ) 
        {
            vertexIndex = face[ faceIndices[ j ] ];
            face.vertexColors[ j ] = cubeGeometry.colors[ vertexIndex ];
        }
    }
    
    cube = new THREE.Mesh( cubeGeometry, vertexColorMaterial );
    

提交回复
热议问题