Currently, I am utilizing the code below to center an object within the scene. While it works perfectly with the json loader, the issue arises when using either OBJLoader
or OBJMTLLoader
.
function modelLoadedCallback(geometry, materials) {
// Create the object based on the loaded geometry and materials, allowing for multiple materials via MeshFaceMaterials.
// Please note that materials may contain references to texture images that could finish loading later.
var object = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
// Determine the range of x, y, and z values in the geometry vertices.
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 a 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();
}
This is causing a TypeError: s is undefined
, preventing my model from displaying on the scene. What could be the issue here? Are there any alternate methods available to center the object using OBJLoader
or OBJMTLLoader
?