colors - 为 Three.js BoxGeometry 的面着色

标签 colors three.js face

我看到了一些访问 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 论坛上的以下帖子中的更多信息。
https://discourse.threejs.org/t/three-geometry-will-be-removed-from-core-with-r125/22401

关于colors - 为 Three.js BoxGeometry 的面着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67989801/

相关文章:

PHP - 替换图像中的颜色

c++ - 如何从 C++/Ncurses 中获得更多颜色

javascript - 在three.js中渲染多边形

javascript - 如何使用 Three.js 改变立方体的颜色

python - 如何在 Maya 中找到面邻居?

ios - 使用 Swift 访问 Microsoft Face API IOS

delphi - 使用 cairo、librsvg 和 delphi 绘制 SVG,更改所有路径的颜色

matlab - 为什么颜色会随着 MATLAB轮廓循环而变化?

javascript - 如果使用循环,则在 threejs 中旋转球体不起作用

java - Microsoft Face API 中的 "Decoding error, image format unsupported"