Three Js update vertices,normals and indices

this Code renders this : render of the code
the problem i'm having is can't update the vertices, in my code i'm trying to update three points just to see if it works. the geometry has a normal vector and indices so maybe i should update those too.

    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;
      }

Upvotes: 0

Views: 491

Answers (1)

prisoner849
prisoner849

Reputation: 17586

Seems, you have to change the buffer attribute with positions, not the initial array. Thus in your update it should look like this:

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;
}

Upvotes: 1

Related Questions