如何居中和缩放对象threejs

Dio*_*res 7 html javascript 3d three.js

我使用以下代码来缩放和居中使用ObjectLoader加载的msgpack压缩对象,但它无法正常工作.我认为我的对象有一个旋转,因此导致奇怪的行为.在某些对象上,它成功地居中,但在其他对象上,居中是偏移的,缩放也不正确.

在此片段中,结果是ObjectLoader中的场景.我的想法是对象形成的不是很好,但我不确定.我希望图像上的表格或任何其他用户输入的网格位于网格的顶部,居中并缩放,以使最大尺寸为1个单位.

每个方块的尺寸为0.25,轴线为0,0,0 http://i.stack.imgur.com/fkKYC.png

    // result is a threejs scene        
    var geometry = result.children[0].geometry;
    var mesh = result.children[0];
    geometry.computeBoundingBox();
    var middle = new THREE.Vector3();
    middle.x        = ( geometry.boundingBox.max.x + geometry.boundingBox.min.x ) / 2;
    middle.y        = -geometry.boundingBox.min.y;
    middle.z        = ( geometry.boundingBox.max.z + geometry.boundingBox.min.z ) / 2;
    middle.negate();
    mesh.position.copy(middle);
    // scales the mesh up to maxsize
    var maxSize = 1;
    // gets the biggest axis
    var maxVal = geometry.boundingBox.max.x - geometry.boundingBox.min.x;
    if (maxVal < geometry.boundingBox.max.y - geometry.boundingBox.min.y) {
        maxVal = geometry.boundingBox.max.y - geometry.boundingBox.min.y;
    }
    if (maxVal < geometry.boundingBox.max.z - geometry.boundingBox.min.z) {
        maxVal = geometry.boundingBox.max.z - geometry.boundingBox.min.z;
    // scales the current size proportional to the maxval, times maxsize
    mesh.scale.divideScalar(maxVal * maxSize);

    self.scene.add(result);
Run Code Online (Sandbox Code Playgroud)

bjo*_*rke 5

而不是调用的geometry.computeBoundingBox();电话geometry.center();,那么你不需要middle.x或者middle.z,你可以直接调用mesh.translateY(),而不是摆弄middle可言