setFromObject(mesh)有时会返回错误的值

Jor*_*mus 5 javascript bounding-box three.js

THREE.Box3.setFromObject(*object*)返回错误的值.向您展示的最佳方式是向您展示我的工作方式:

我从顶点创建2个网格.第一个是triangle()功能,另一个是trapezoidForm().

var triangle = function (base, height) {

    return [
        new THREE.Vector2(0,  -height / 2),
        new THREE.Vector2(-base / 2,  height / 2),
        new THREE.Vector2(base / 2,  height / 2)
    ];
}
var trapezoidForm = function (base, upperBase, height) {

    return [

        new THREE.Vector2(-base / 2,  height / 2),
        new THREE.Vector2(-upperBase / 2,  -height / 2),
        new THREE.Vector2(upperBase / 2,  -height / 2),
        new THREE.Vector2(base / 2,  height / 2),
    ];

}
Run Code Online (Sandbox Code Playgroud)

我使用返回的值来创建我的网格:

var material    = new THREE.MeshPhongMaterial({ color: 0x666666, /*specular: 0x101010*//*, shininess: 200*/ });
var shape       = new THREE.Shape(vertices);
var mesh        = new THREE.Mesh(new THREE.ShapeGeometry(shape), material);
Run Code Online (Sandbox Code Playgroud)

并使用它将它放在场景中,并创建一个边界框:

mesh.position.set(posX, 0, posZ);
mesh.rotation.set(-Math.PI / 2, 0, 0);
boundingBox.setFromObject(mesh);
Run Code Online (Sandbox Code Playgroud)

现在,我想找到我的2个形状的中心.足够简单:我带边界框,并计算它.像这样:

var centerX = (boundingBox.max.x + boundingBox.min.x) * 0.5;
var centerZ = (boundingBox.max.z + boundingBox.min.z) * 0.5;
Run Code Online (Sandbox Code Playgroud)

这是它出错的地方:对于三角形,它计算出正确的位置,但对于梯形,它会变得混乱.

下面是控制台的打印屏幕.前三个顶点用于三角形,后面是边界框.接下来的4个是梯形,再次是边界框.对于顶点:第一个数字是X-coord,第二个是Z-coord.

控制台日志,显示问题

期望的结果:第二个边界框应该返回如下内容:

max: X: 200
     Z: 200

min: X: -200
     Z: -100
Run Code Online (Sandbox Code Playgroud)

显示当前状态的图像(三角形中间有减号,梯形没有):

情况

Jor*_*mus 0

最后我自己找到了解决方案:

在重新定位或旋转边界框之前,我必须创建边界框:

//Boundingbox
boundingBox.setFromObject(mesh);

mesh.position.set(posX, 0, posZ);
mesh.rotation.set(-Math.PI / 2, 0, 0);
Run Code Online (Sandbox Code Playgroud)

代替:

mesh.position.set(posX, 0, posZ);
mesh.rotation.set(-Math.PI / 2, 0, 0);
//Boundingbox
boundingBox.setFromObject(mesh);
Run Code Online (Sandbox Code Playgroud)

三角形之所以没有引起问题,是因为它是在 0,0 处渲染的。