如何获取 three.js 中整个场景的 boundingSphere?

how to get the boundingSphere for a whole scene in three.js?

如何获取three.js中整个场景的包围球? 我可能会尝试获取每个对象的包围球并计算它们的并集,但我认为可能有更直接的方法。

有多种方法可以动态获取多个对象的 boundingSphere。您可以首先获取所有这些边界框,然后创建该边界框的球体...这是我在 boundingSphere of a boundingBox.

上塑造的示例 fiddle

基本上你把所有的几何体都放在一个Group中,你得到这个组的Box3,然后你从Box3做getBoundingSphere并定位在中心。 fiddle 中的代码是这样的。

let g = new THREE.Group();
scene.add(g);
for (let i = 0; i < 5; i++) {

    // geometry
    var geometry = new THREE.BoxGeometry(20, 20, 20);

    // material
    var material = new THREE.MeshToonMaterial({
        color: 0xff0000,
        opacity: 0.7,
    });

    // mesh
    mesh = new THREE.Mesh(geometry, material);
    mesh.position.set(100 * Math.random(), 100 * Math.random(), 100 * Math.random());
    g.add(mesh);
}

//g.updateWorldMatrix(true);
var gridHelper = new THREE.GridHelper(400, 40, 0x0000ff, 0x808080);
gridHelper.position.y = 0;
gridHelper.position.x = 0;
scene.add(gridHelper);

let bbox = new THREE.Box3().setFromObject(g);
let helper = new THREE.Box3Helper(bbox, new THREE.Color(0, 255, 0));
scene.add(helper);

const center = new THREE.Vector3();
bbox.getCenter(center);

let bsphere = bbox.getBoundingSphere(new THREE.Sphere(center));
let m = new THREE.MeshStandardMaterial({
    color: 0xffffff,
    opacity: 0.3,
    transparent: true
});
var geometry = new THREE.SphereGeometry(bsphere.radius, 32, 32);
let sMesh = new THREE.Mesh(geometry, m);
scene.add(sMesh);
sMesh.position.copy(center);

EDITED:如果你想在包含灯光的场景中包含 boundingSphere(这可能会让你得到一个巨大的球体),只需从 let bbox = new THREE.Box3().setFromObject(scene)