包围盒&包围盒辅助器
包围盒是几何体在三维空间中的一个边界框,用于描述几何体的大小和位置。包围盒辅助器是用于显示包围盒的辅助器。
我们先获取几何体,然后计算包围盒,最后设置包围盒辅助器:
// 加载 gltf 模型
const gltfLoader = new GLTFLoader()
gltfLoader.load('/model/Duck.glb', (gltf) => {
scene.add(gltf.scene)
// 获取 duck 模型
const duckMesh = gltf.scene.getObjectByName('LOD3spShape')
const duckGeometry = duckMesh.geometry
// 计算包围盒并设置包围盒辅助器
duckGeometry.computeBoundingBox()
const boundingBox = duckGeometry.boundingBox
const boxHelper = new THREE.Box3Helper(boundingBox, 0x00ff00)
scene.add(boxHelper)
})
此时发 现包围盒非常大。
这是因为世界矩阵没有更新,导致包围盒的计算不准确。
我们可以先更新模型的世界矩阵,然后更新包围盒辅助器:
// 加载 gltf 模型
const gltfLoader = new GLTFLoader()
gltfLoader.load('/model/Duck.glb', (gltf) => {
scene.add(gltf.scene)
// 获取 duck 模型
const duckMesh = gltf.scene.getObjectByName('LOD3spShape') as THREE.Mesh
const duckGeometry = duckMesh.geometry
// 计算包围盒
duckGeometry.computeBoundingBox()
// 更新 duck 模型的世界矩阵
duckMesh.updateWorldMatrix(true, true)
// 设置包围盒辅助器
const duckBox = duckGeometry.boundingBox as THREE.Box3
// 更新包围盒辅助器
duckBox.applyMatrix4(duckMesh.matrixWorld)
const boxHelper = new THREE.Box3Helper(duckBox, 0x00ff00)
scene.add(boxHelper)
})
![The bounding box of the duckThe bounding box of the duck](https://img.wukaipeng.com//2025/04/29-101957-5kIT08-
本节示例代码:https://github.com/wukaipeng-dev/threejs-demo/blob/main/03-geometry/src/main-box.ts