为 Three.js BoxGeometry 的面着色

Coloring faces of a Three.js BoxGeometry

我看到一些访问 THREE.BoxGeometry 面孔的解决方案是这样的:

var geometry = new THREE.BoxGeometry(n,n,n)
let faces = geometry.faces;
for (let face of faces) {
  face.color.set(Math.random() * 0xffffff);
}

但似乎 faces-array 在当前 Three.js 版本 r129 (Uncaught TypeError: faces is not iterable) 中不存在。

我怎样才能简单地给立方体的六个面着色?

试试看:

let camera, scene, renderer, mesh;

init();
animate();

function init() {

    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
    camera.position.z = 1;

    scene = new THREE.Scene();

    const geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 ).toNonIndexed();
        
    // vertexColors must be true so vertex colors can be used in the shader
        
    const material = new THREE.MeshBasicMaterial( { vertexColors: true } ); 
        
    // generate color data for each vertex
        
    const positionAttribute = geometry.getAttribute( 'position' );
        
    const colors = [];
    const color = new THREE.Color();
        
    for ( let i = 0; i < positionAttribute.count; i += 3 ) {
        
            color.set( Math.random() * 0xffffff );
            
            // define the same color for each vertex of a triangle
            
            colors.push( color.r, color.g, color.b );
            colors.push( color.r, color.g, color.b );
            colors.push( color.r, color.g, color.b );
        
    }
        
    // define the new attribute
        
    geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( colors, 3 ) );

    mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

}

function animate() {

    requestAnimationFrame( animate );

    mesh.rotation.x += 0.01;
    mesh.rotation.y += 0.02;

    renderer.render( scene, camera );

}
body {
      margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.129.0/build/three.js"></script>

以前的几何格式已从 r125 的核心中删除。更多信息请参见 three.js 论坛中的 post。

https://discourse.threejs.org/t/three-geometry-will-be-removed-from-core-with-r125/22401