How to center and scale a threejs object

I use the following code to scale and center a compressed msgpack object loaded using ObjectLoader and it does not work. I think my object has a turn on it and therefore causes strange behavior. On some objects, it is successfully centered, but on others, the centering is shifted and scaling is also incorrect.

In this snippet, the result is a scene from ObjectLoader. I thought the object was not very well formed, but I'm not sure. I wanted the table in the image or any other user entered into the grid to be at the top of the grid, centered and scaled so that the maximum size was 1 unit.

Each square measures 0.25, the axis is 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); 
+7
javascript html 3d
source share
1 answer

Instead of calling geometry.computeBoundingBox(); call geometry.center(); you don’t need middle.x or middle.z , and you can just call mesh.translateY() and not mess with middle at all

+5
source share

All Articles