【问题标题】:How to set face color according to vertex in three.js如何在three.js中根据顶点设置人脸颜色
【发布时间】:2019-07-20 23:02:04
【问题描述】:

我正在使用 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())

【问题讨论】:

    标签: javascript three.js


    【解决方案1】:

    但是因为面的数量是顶点的两倍

    恐怕这种说法是不正确的。由于重复的顶点正在合并,因此面多于顶点。但是,没有 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-08
      相关资源
      最近更新 更多