three.jsreact-three-fiber

Transform controls not apearing in center of a mesh in THREE.js fiber


I'm using react three fiber and I load some meshes from files and then after load the group they are apart of gets centered. I have an on click handler on the meshes and I attach the transform controls to the mesh clicked. The problem is depending on the file the transform controls end up floating off the mesh rather than being centered on the mesh. These models are random stl files from thingiverse. So my guess is that the origin and position from those files is messed up and their center is just not the center of the mesh. Below is a sample this is a child component to a group.

const StlObject = ({url,matUrl}) => {
    const [selected, SetSelected] = useState(false);

    const geometry = useLoader(STLLoader, url);

    const handleClick = (e) => {
        controls.current.enabled = false;
        transformControls.current.setMode('translate');
        transformControls.current.attach(meshRef.current);
    };

    return (
        <mesh onUpdate={update} rotation={[-Math.PI / 2, 0, 0]} geometry={geometry} ref={meshRef} onClick={handleClick} >
            <meshMatcapMaterial matcap={matUrl} />
        </mesh>
    );
}

Solution

  • I found the solution to this. It was getting the center of the mesh and then re-centering it to 0,0,0 and using the position attribute to put it back where it was. TransformControls were perfect after that.

    // Compute the bounding box of the mesh
    const meshbBox = new THREE.Box3().setFromObject(mesh);
    const meshCenter = meshbBox.getCenter(new THREE.Vector3());
    mesh.geometry.center();
    mesh.position.x = meshCenter.x;
    mesh.position.y = meshCenter.y;
    mesh.position.z = meshCenter.z;