computeBoundingVolume是MeshGeometry类的方法,用于计算几何体的包围盒。
MeshGeometry.prototype.computeBoundingVolume()
该方法没有参数。
该方法没有返回值,但是会修改MeshGeometry对象的boundingVolume属性。
const mesh = new MeshGeometry(vertices, indices);
mesh.computeBoundingVolume();
import { MeshGeometry } from 'yuka';
const meshData = {
  vertices: [
    // vertex positions
  ],
  indices: [
    // indices to form triangles
  ]
};
const mesh = new MeshGeometry(meshData.vertices, meshData.indices);
mesh.computeBoundingVolume();
console.log(mesh.boundingVolume);
计算包围盒需要遍历所有的顶点,获取其中的最大坐标和最小坐标,最后根据这两个坐标建立一个包围盒。具体实现可以参考以下代码片段:
computeBoundingVolume() {
  const positions = this.attributes.position.array;
  const positionStride = this.attributes.position.stride
  const verticesCount = positions.length / positionStride;
  const vec3 = new Vector3();
  const boundingBox = new Box3();
  for (let i = 0; i < verticesCount; i++) {
    vec3.fromArray(positions, i * positionStride);
    boundingBox.expandByPoint(vec3);
  }
  this.boundingVolume.fromBox3(boundingBox);
}
以上代码首先获取网格几何体的顶点坐标,利用Vector3将其转化为向量,然后通过Box3获取当前所有向量的最大坐标和最小坐标,并最终将其构建为包围盒。