Reputation: 3358
am using the following code to visualize the object on the center of the scene, it is working fine for the json loder, if we use OBJLoder
or OBJMTLloder
it is not working
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();
}
it causing TypeError: s is undefined
, so my model is not showing on the scene, what is wrong here?? there is any other method avail to center the object with OBJLoder
or OBJMTLloder
Upvotes: 1
Views: 2443
Reputation: 12632
You do not have to go through the vertices of your model to figure out its center. There is a geometry.computeBoundingBox()
method you can use to compute the bounding box of your geometry. Take a look at http://threejs.org/docs/#Reference/Core/Geometry.
For a Geometry node you should be able to do:
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 + ')' );
Upvotes: 2