繁体   English   中英

如何在three.js中根据顶点设置面部颜色

[英]How to set face color according to vertex in three.js

即时通讯使用Three.js 106版本。 我正在使用一些算法生成地形(从平面几何开始),并且我想根据其veritces z值为地形着色。 这是我到目前为止所得到的

    const geometry = new THREE.PlaneGeometry(
  170,
  150,
  rows,
  cols
);

   ...

for (let y = 0; y < rows + 1; y++) {
  for (let x = 0; x < cols + 1; x++) {
    const pos = x * rows + y;
    const vertex = geometry.vertices[pos];
    if (vertex) {
       vertex.z = myAlgorithm();
    }

但是由于面的数量是顶点的两倍,所以它不像顶点那么简单

geometry.faces[pos].color.set(myColorAlgorithm())

但是由于面的数量是顶点的两倍

恐怕这句话是不正确的。 由于合并的顶点数多,因此面数多于顶点数。 但是,没有2:1关系。

尝试使用BufferGeometry而不是Geometry因为使用纯顶点数据应该会使代码更清晰。 此代码如下所示:

const geometry = new THREE.PlaneBufferGeometry( 1, 1, rows, cols );

const position = geometry.attributes.position;

const colors = [];
const color = new THREE.Color();

for ( let i = 0; i < position.count; i ++ ) {

    const z =  Math.random() * 0.2; // instead of myAlgorithm()

    position.setZ( i, z );

    const s = z * 5; // values  in the range [0,1]

    color.setHSL( 0.4, s, 0.5 );

    colors.push( color.r, color.g, color.b );

}

geometry.addAttribute( 'color', new THREE.Float32BufferAttribute( colors, 3 ) );

现场演示: https : //jsfiddle.net/zj8d1m2v/3/

three.js R106

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM