Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Object3D loaded using OBJMTLLoader

I am building an application which allows users to upload 3D models in the obj/mtl format. The admin displays a preview of what the loaded object will look like in our viewer. I would like to provide controls for the user to set the initial y-position of the loaded object, and the initial z position of the camera. I have the camera part worked out, but I'm having no luck with the y-position. My code:

var obj3d;

loader.load( model_obj, model_mtl, function ( object ) {
    object.position.y = y_init;
    scene.add( object );
    render();

    obj3d = object;

    $('#initial_y').change(function() {
      obj3d.position.y = $(this).val();
    });

}, onProgress, onError );

The issue seems to be that once I am outside the load function, the reference to the Object3D is no longer available. The code above gives a javascript error:

Cannot access property 'position' of undefined.

Any help is greatly appreciated!

like image 699
Vince Avatar asked Oct 08 '15 21:10

Vince


1 Answers

The comment from @mrdoob led me to solving this myself. My variable obj3d was indeed out of scope when the jquery callback was triggered. I was able to resolve it by moving the variable declaration to the global scope.

Additionally, the reason I wasn't seeing the changes applied immediately in the three.js scene was because I needed to call the render() function.

$('#initial_y').change(function() {
    obj3d.position.y = $(this).val();
    render();
});

Hopefully this will help someone else. Thanks for pointing me in the right direction!

like image 135
Vince Avatar answered Oct 02 '22 12:10

Vince