2

I just started working with three.js recently and I finally have my models loading in properly. However, looking at the examples I noticed that the centering in most of the examples is done with coding like this

object.position.y = - 95;

That works fine for the example's purpose but I'm loading multiple objects of different sizes and I don't want to hard code a value for every single model. So my question is, how do you center an object dynamically?

I saw geometry.center was a way to achieve this but I couldn't find any examples and I don't understand how to add that into this example

http://threejs.org/examples/#webgl_loader_obj_mtl

Any suggestions, tutorials, tips, or examples would be great. Thanks!

Tony
  • 107
  • 1
  • 2
  • 8

1 Answers1

2

If the pivot point of your models is at the vertical center of your model, you can use this general approach:

//object.geometry.center();
var box = new THREE.Box3().setFromObject( object )
var boundingBoxSize = box.max.sub( box.min );
var height = boundingBoxSize.y;
object.position.y = - height / 2;

And if the geometry is already shifted, you can re-center it using geometry.center().

Falk Thiele
  • 4,424
  • 2
  • 17
  • 44
  • Thank you for your reply, that code is working with a small change to the last line: object.position.y = (height / 2) *-1; But the issue now is the zoom being set like this camera.position.z = 250; and camera.position.z = 300; How would I do basically the same thing with the camera's zoom so it fits the object to the screen? – Tony Mar 07 '16 at 23:21
  • You are right i will correct the code. Your second question is answered here: http://stackoverflow.com/a/23361117/4977165 – Falk Thiele Mar 07 '16 at 23:33
  • In that post height equals the object height? How would I get that? – Tony Mar 07 '16 at 23:52
  • The height is the ```boundingBoxSize.y```, like in the code Ive posted above. – Falk Thiele Mar 07 '16 at 23:58
  • Ok, I understand now. I was changing the code in the wrong place, it's working now. Thank you for your help! – Tony Mar 07 '16 at 23:59