首页 > 解决方案 > 如何在threejs v128+ 中遍历几何的顶点?

问题描述

我正在查看一些旧代码,它们执行以下操作以稍微随机化几何的顶点:

  let geometry = new THREE.DodecahedronGeometry(size, 1);
  geometry.vertices.forEach(function(v) {
    v.x += 0 - Math.random() * (size / 4);
    v.y += 0 - Math.random() * (size / 4);
    v.z += 0 - Math.random() * (size / 4);
  });

但是在最近的threejs版本中,几何上没有顶点属性。那么,您将如何使用现代版本实现这一目标?

标签: three.js

解决方案


这是我确定的解决方案。似乎 threejs 发生了变化,不再将每个顶点存储为单个点,而是让多个点(在不同的面上)在同一个顶点处相遇。所以为了扭曲十二面体,我必须首先识别同一顶点上的每个点,并使用哈希图以相同的方式修改它们。

interface IVertices {
  [index: string]: {
    x: number;
    y: number;
    z: number;
  };
}

const geometry = new THREE.DodecahedronGeometry(size, 0);
const positionAttribute = geometry.getAttribute('position');
const point = new THREE.Vector3();
const vertices: IVertices = {};

// Go thru all points and collect points on same vertex with a hashmap
for (let i = 0; i < positionAttribute.count; i++) {
  point.fromBufferAttribute(positionAttribute, i); 
  const key = [point.x, point.y, point.z].join(',');
  if (!vertices[key]){
    vertices[key] = {
      x: point.x += Math.random() * size * warpFactor,       
      y: point.y += Math.random() * size * warpFactor,
      z: point.z += Math.random() * size * warpFactor,
    };
  }
  // Modify all points on same vertex with same deformation
  const { x, y, z } = vertices[key];
  positionAttribute.setXYZ(i, x, y, z);
}


推荐阅读