在threejs中将模型设置在场景的中心

时间:2014-06-27 10:53:19

标签: javascript three.js

使用以下代码可视化场景中心的对象,它对json loder工作正常,如果我们使用OBJLoderOBJMTLloder它不能正常工作

function modelLoadedCallback(geometry, materials) {

    /* create the object from the geometry and materials that were loaded.  There
       can be multiple materials, which can be applied to the object using MeshFaceMaterials.
       Note tha the material can include references to texture images might finish
       loading later. */

    var object = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));

    /* Determine the ranges of x, y, and z in the vertices of the geometry. */

    var xmin = Infinity;
    var xmax = -Infinity;
    var ymin = Infinity;
    var ymax = -Infinity;
    var zmin = Infinity;
    var zmax = -Infinity;
    for (var i = 0; i < geometry.vertices.length; i++) {
        var v = geometry.vertices[i];
        if (v.x < xmin)
            xmin = v.x;
        else if (v.x > xmax)
            xmax = v.x;
        if (v.y < ymin)
            ymin = v.y;
        else if (v.y > ymax)
            ymax = v.y;
        if (v.z < zmin)
            zmin = v.z;
        else if (v.z > zmax)
            zmax = v.z;
    }

    /* translate the center of the object to the origin */
    var centerX = (xmin+xmax)/2;
    var centerY = (ymin+ymax)/2; 
    var centerZ = (zmin+zmax)/2;
    var max = Math.max(centerX - xmin, xmax - centerX);
    max = Math.max(max, Math.max(centerY - ymin, ymax - centerY) );
    max = Math.max(max, Math.max(centerZ - zmin, zmax - centerZ) );
    var scale = 10/max;
    object.position.set( -centerX, -centerY, -centerZ );
    console.log("Loading finished, scaling object by " + scale);
    console.log("Center at ( " + centerX + ", " + centerY + ", " + centerZ + " )");

    /* Create the wrapper, model, to scale and rotate the object. */

    model = new THREE.Object3D();
    model.add(object);
    model.scale.set(scale,scale,scale);
    rotateX = rotateY = 0;
    scene.add(model);
    render();

}

导致TypeError: s is undefined,所以我的模型没有在场景中显示,这里有什么问题?可以使用OBJLoderOBJMTLloder

将对象置于中心位置

1 个答案:

答案 0 :(得分:2)

您无需通过模型的顶点来确定其中心。您可以使用geometry.computeBoundingBox()方法计算几何体的边界框。看看http://threejs.org/docs/#Reference/Core/Geometry

对于Geometry节点,您应该能够:

geometry.computeBoundingBox ();
var bBox = geometry.boundingBox;
alert('bounding box coordinates: ' + 
    '(' + bBox.min.x + ', ' + bBox.min.y + ', ' + bBox.min.z + '), ' + 
    '(' + bBox.max.x + ', ' + bBox.max.y + ', ' + bBox.max.z + ')' );