Search code examples
3dthree.js.obj

Understanding the position of .OBJ 3D objects


I'm trying to make a simple THREE.js-powered visualization of what various objects look like in scale to the Empire State Building. So I bought this very reasonably priced model for $2, which comes in several formats including .obj. I then used THREE's OBJLoader to add it to the scene.

    container = document.getElementById("city");
    camera = new THREE.PerspectiveCamera( 60, 1, 1, 2000 );
    camera.position.set( 100, 0, -100 );

    scene = new THREE.Scene();
    scene.background = new THREE.Color( 0x87CEEB );

    var ambientLight = new THREE.AmbientLight( 0xcccccc, 0.4 );
    scene.add( ambientLight );

    // load the ESB model
    var loader = new THREE.OBJLoader();

    loader.load(
        'data/esb.obj',
        function ( object ) { // called when resource is loaded
            ESB = object;
            scene.add( object );
        },
        function ( xhr ) { // called when loading is in progresses
            console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
        },
        function ( error ) {
            console.log(error);
        }
    );

This successfully loads the OBJ file -- demo here. (I would put on CodePen but don't have rights to redistribute the OBJ. Please don't steal it!)

As you can see, however, while I added some Axis Helpers that are vaguely visible in the distance, the ESB floats in on its side from the left:

enter image description here

Clearly I don't understand the .obj specification that well, though I've tried to read up on it. My questions are:

  • Do OBJ files have absolute coordinates, such that, for some reason, the ESB would be way off from the center of <0,0,0>?
  • Why is it moving? Can OBJ files have momentum, or is this an artifact of something I'm doing in Three.js?

Thanks as always!


Solution

  • Yes, the model of the ESB is not centered at the origin. You can easily verify this if you import it into Blender. Try to reposition the loaded OBJ to the center of the scene via:

    var boundingBox = new THREE.Box3().setFromObject( object );
    boundingBox.getCenter( object.position ).negate();
    

    The movement of the object is not related to the OBJ format. I guess some application level code causes this behavior.