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

时间:2015-11-27 13:04:21

标签: javascript three.js bounding-box

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),
    ];

}

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

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);

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

mesh.position.set(posX, 0, posZ);
mesh.rotation.set(-Math.PI / 2, 0, 0);
boundingBox.setFromObject(mesh);

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

var centerX = (boundingBox.max.x + boundingBox.min.x) * 0.5;
var centerZ = (boundingBox.max.z + boundingBox.min.z) * 0.5;

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

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

Console log, showing the problem

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

max: X: 200
     Z: 200

min: X: -200
     Z: -100

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

state of situation

1 个答案:

答案 0 :(得分:0)

最终自己找到了解决方案:

在重新定位或旋转之前,我必须创建我的boundingBox:

//Boundingbox
boundingBox.setFromObject(mesh);

mesh.position.set(posX, 0, posZ);
mesh.rotation.set(-Math.PI / 2, 0, 0);

而不是:

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

三角形没有引起问题的原因是因为它是在0,0上呈现的。