多个几何体的包围盒
创建 3 个小球:
// 创建三个不同颜色的球体
const sphereGeometry = new THREE.SphereGeometry(1, 32, 32) // 复用几何体
const spheres = [
{ color: 0x00ff00, position: -3 }, // 左侧绿色
{ color: 0x0000ff, position: 0 }, // 中间蓝色
{ color: 0xff0000, position: 3 }, // 右侧红色
].map(({ color, position }) => {
const material = new THREE.MeshBasicMaterial({ color })
const sphere = new THREE.Mesh(sphereGeometry, material)
sphere.position.x = position
scene.add(sphere)
return sphere
})
第一种方式:计算包围盒 + 更新世界矩阵
const box = new THREE.Box3()
for (const sphere of spheres) {
// 计算包围盒
sphere.geometry.computeBoundingBox()
const box3 = sphere.geometry.boundingBox
// 更新世界矩阵
sphere.updateWorldMatrix(true, true)
box3?.applyMatrix4(sphere.matrixWorld)
box3 && box.union(box3)
}
const boxHelper = new THREE.Box3Helper(box, 0xff0000)
scene.add(boxHelper)
第二种方式:直接使用 setFromObject
方法,更加简单
const box = new THREE.Box3()
for (const sphere of spheres) {
const box3 = new THREE.Box3().setFromObject(sphere)
box3 && box.union(box3)
}
const boxHelper = new THREE.Box3Helper(box, 0xff0000)
scene.add(boxHelper)