トップへ(mam-mam.net/)

How to Update 3D Mesh Vertex Positions in Real Time with Three.js [Detailed Guide & Sample Code]

Japanese

How to Update 3D Mesh Vertex Positions in Real Time with Three.js [Detailed Guide & Sample Code]

By using Three.js, you can dynamically modify the vertex positions of a 3D mesh to create realistic motion.
This article explains how to update vertex coordinates, adjust the corresponding normal vectors, and correctly set needsUpdate.

Updating Vertex Positions of a 3D Mesh (Three.js [r145])

After modifying vertex positions, you must call computeVertexNormals() to recalculate the normal vectors; otherwise, shadows will not be rendered correctly.
In addition,
geometry.attributes.position.needsUpdate = true;
must be set to notify Three.js that the vertex data has been updated.

Rotate with left mouse drag, move the camera with right mouse drag, and zoom with the mouse wheel.
On touch devices: swipe to rotate, drag with two fingers to move the camera, and pinch in/out to zoom.

Source Code

function renderLoop () {
  requestAnimationFrame(renderLoop);
  // Update the Y‑coordinates of the mesh vertices here
  phase += 0.05;
  for (let z = 0; z < pointnum; z++) {
    for (let x = 0; x < pointnum; x++) {
      meshWave.geometry.attributes.position.array[(z * pointnum + x) * 3 + 1] =
        Math.cos(x * Math.PI / 8 + phase) * Math.sin(z * Math.PI / 8 + phase) * heightSize;
    }
  }
  meshWave.geometry.computeVertexNormals();
  meshWave.geometry.attributes.position.needsUpdate = true;
  renderer.render(scene, camera);
}

Back to the list of 3D JavaScript content