使用THREE.Mesh时如何修复'n.computeBoundingBox is not a function'错误?
问题根源
错误TypeError: n.computeBoundingBox is not a function是因为你直接把Autodesk Viewer的FragmentProxy实例传给了THREE.Mesh构造函数。THREE.Mesh要求第一个参数必须是THREE.Geometry或THREE.BufferGeometry类型的几何体,而FragmentProxy是Viewer封装的代理类,没有Three.js几何体必备的computeBoundingBox方法,导致Viewer遍历场景计算可视范围时触发报错。
解决思路与修正代码
要基于Viewer的Fragment创建独立的Three.js Mesh,必须先从Fragment中提取原始几何体,再按Three.js规则创建Mesh:
fragIds.forEach(function(fragId){ const fragProxy = Viewer.impl.getFragmentProxy(Viewer.model, fragId); fragProxy.getAnimTransform(); // 1. 获取Fragment对应的原始几何体 const fragList = Viewer.model.getFragmentList(); const originalGeometry = fragList.getGeometry(fragId); // 复制几何体,避免修改原模型的原始数据 const geometry = originalGeometry.clone(); // 2. 获取原Fragment的世界变换矩阵 const wcsMatrix = new THREE.Matrix4(); fragProxy.getWorldMatrix(wcsMatrix); // 3. 创建Three.js Mesh并应用变换 const material = new THREE.MeshPhongMaterial({ color: 0xff0000 }); const mesh = new THREE.Mesh(geometry, material); // 应用原Fragment的位置、旋转、缩放 mesh.applyMatrix4(wcsMatrix); // 自定义缩放调整 mesh.scale.y = 2; // 额外调整位置 mesh.position.set(100, 0, 0); // 4. 添加到场景并更新 Viewer.impl.scene.add(mesh); mesh.updateMatrixWorld(); }); Viewer.impl.sceneUpdated(true);
额外提示
- 如果不需要保留原Fragment的精细几何体,可基于其包围盒创建
BoxGeometry等简单几何体,适合做高亮占位用 - 尽量使用Viewer内置的Three.js对象(
Viewer.impl.threejs下的核心类),避免外部引入的Three.js版本与Viewer内置版本冲突 - 若只是想修改原Fragment的材质,无需创建新Mesh,直接通过
fragProxy.updateMaterial()修改即可,性能更优
内容的提问来源于stack exchange,提问作者Alpesh Panchal
相关产品推荐
相关产品推荐

