THREE.js Fiber中Transform Controls未居中于Mesh问题求助
解决React Three Fiber中STL模型Transform Controls偏离问题
部分来自Thingiverse的STL模型原点未位于几何中心,导致绑定Transform Controls后控件偏离模型。以下是修正方案:
- 修正几何体原点:加载STL后计算几何体包围盒,将几何体平移至原点,同时调整Group位置以保持模型在Group中居中。
- 确保Transform Controls绑定逻辑正确:修正后原点对齐的几何体,绑定控件后会自动居中。
修改后的组件代码示例:
import { useState, useEffect, useRef } from 'react'; import { useLoader } from '@react-three/fiber'; import { STLLoader } from 'three/addons/loaders/STLLoader.js'; import * as THREE from 'three'; const StlObject = ({ url, matUrl }) => { const [selected, setSelected] = useState(false); const meshRef = useRef(null); const groupRef = useRef(null); const geometry = useLoader(STLLoader, url); // 修正几何体原点 useEffect(() => { if (!geometry) return; geometry.computeBoundingBox(); const boundingBox = geometry.boundingBox; const center = boundingBox.getCenter(new THREE.Vector3()); // 将几何体平移到全局原点 geometry.translate(-center.x, -center.y, -center.z); // 调整Group位置,让模型在Group中保持居中 if (groupRef.current) { groupRef.current.position.set(center.x, center.y, center.z); } }, [geometry]); const handleClick = (e) => { controls.current.enabled = false; transformControls.current.setMode('translate'); transformControls.current.attach(meshRef.current); }; const update = () => { // 自定义更新逻辑 }; return ( <group ref={groupRef}> <mesh ref={meshRef} onUpdate={update} rotation={[-Math.PI / 2, 0, 0]} geometry={geometry} onClick={handleClick} > <meshMatcapMaterial matcap={matUrl} /> </mesh> </group> ); }; export default StlObject;
关键说明
computeBoundingBox():计算几何体的轴对齐包围盒,获取模型的实际范围。geometry.translate():将几何体的中心移至全局原点,确保Transform Controls绑定后控件与模型中心对齐。- Group位置调整:通过设置Group的position抵消几何体的平移,保证模型在父容器中仍处于居中状态。
内容的提问来源于stack exchange,提问作者James Celestino
相关产品推荐
相关产品推荐

