首页 > 解决方案 > 三个Js更新顶点、法线和索引

问题描述

此代码呈现: 呈现代码
我遇到的问题是无法更新顶点,在我的代码中,我试图更新三个点以查看它是否有效。几何图形有一个法线向量和索引,所以也许我也应该更新它们。

    export default (scene) => {
      const noise = new Noise(Math.random());
      const geometry = new THREE.BufferGeometry();
      let indices = [];
      let vertices = [];
      let normals = [];
      const size = 50;
      const segments = 32;
      const halfSize = size / 2;
      const segmentSize = size / segments;
      let xoff = 0,
        yoff = 0,
        zofff = 0.01;
      for (let i = 0; i <= segments; i++) {
        const y = i * segmentSize - halfSize;
        yoff += 0.01;
        for (let j = 0; j <= segments; j++) {
          xoff += 0.01;
          const dd = noise.perlin3(xoff, yoff, zofff) * 3;
          const x = j * segmentSize - halfSize;
          vertices.push(x, dd, -y);
          normals.push(1, 0, 1);
        }
      }
      for (let i = 0; i < segments; i++) {
        for (let j = 0; j < segments; j++) {
          const a = i * (segments + 1) + (j + 1);
          const b = i * (segments + 1) + j;
          const c = (i + 1) * (segments + 1) + j;
          const d = (i + 1) * (segments + 1) + (j + 1);
          // generate two faces (triangles) per iteration
          indices.push(a, b, d); // face one
          indices.push(b, c, d); // face two
        }
      }
      geometry.setIndex(indices);
      geometry.addAttribute(
        'position',
        new THREE.Float32BufferAttribute(vertices, 3).setDynamic(true),
      );
      geometry.addAttribute(
        'normal',
        new THREE.Float32BufferAttribute(normals, 3).setDynamic(true),
      );
      const material = new THREE.MeshPhongMaterial({
        side: THREE.DoubleSide,
        wireframe: true,
        color: '0xffffff',
      });
      const mesh = new THREE.Mesh(geometry, material);
      scene.add(mesh);
      let zoff = 0;
      function update() {
        zoff += 0.1;
        vertices[1] = Math.random() * 10;
        vertices[4] = Math.random() * 10;
        vertices[7] = Math.random() * 10;
        mesh.geometry.attributes.position.needsUpdate = true;
        mesh.geometry.verticesNeedUpdate = true;
      }

标签: three.js

解决方案


似乎,您必须使用位置而不是初始数组来更改缓冲区属性。因此,在您的更新中,它应该如下所示:

function update() {
    zoff += 0.1; // the reason to have it here is unknown
    geometry.attributes.position.setY(0, Math.random() * 10);
    geometry.attributes.position.setY(1, Math.random() * 10);
    geometry.attributes.position.setY(2, Math.random() * 10);
    geometry.attributes.position.needsUpdate = true;
}

推荐阅读