three.js

Edges geometry - Draw boundary edges from a mesh that is not located at the origin


So I have a cube mesh placed at a random location:

mesh.position.set(target.x, target.y, target.z);
scene.add(mesh);

I want to draw its edge lines in that location. I tried using EdgeGeometry as suggest. However, it only works when the mesh is set at the origin but the efforts for updating its buffer geometry doesn't make it work!

const newBox = mesh.geometry.clone();
newBox.applyQuaternion(mesh.quaternion);
    newBox.attributes.position =
      newBox.attributes.position.applyMatrix4(mesh.matrixWorld);
newBox.attributes.position.needsUpdate = true;
const edges = new THREE.EdgesGeometry(newBox);
    const lines = new THREE.LineSegments(
      edges,
      new THREE.LineBasicMaterial({ color: "red" })
    );
    scene.add(lines);

mesh the outline edges are placed at the same location for all meshes. I've also rotated the original mesh so the outline should be rotated.

As mentioned before that's what I tried


Solution

  • This documentation need to be more specific. Apparently matrices are auto updated after rendering when added to the scene!!! enter image description here thus, update the mesh matrix yourself after being added to the scene:

    mesh.updateMatrix();
    

    so later you can ensure that you are passing a matrix with updated values to the applyMatrix4() command! You can do it to the lines.geometry or straight forward to the lines it self:

    lines.applyMatrix4(mesh.matrix);
    

    full code as following:

     const boxGeo = new THREE.BoxGeometry(
          10,
          10,
          10,
        );
    const mesh = new THREE.Mesh(
          boxGeo,
          new THREE.MeshBasicMaterial({
            color: "blue",
          })
        );
    mesh.rotation.y = Math.PI / 4;
    mesh.position.set(target.x, target.y, target.z);//your coordinates
    mesh.updateMatrix(); //!! important!!
    scene.add(mesh);
    
    const newBox = mesh.geometry.clone();
    const edges = new THREE.EdgesGeometry(newBox);
        const lines = new THREE.LineSegments(
          edges,
          new THREE.LineBasicMaterial({ color: "red" })
        );
    scene.add(lines);
    lines.applyMatrix4(mesh.matrix);
    

    meshes