Utkarsh Zaveri
Utkarsh Zaveri

Reputation: 151

Three.js | Unable to access imported object property outside loader.load

I want to move an imported object(.obj) on every render/animate function call. So, I made a copy of the object so as to access it outside the loader.load but everytime I call companion.position I'm getting this error. ( companion is a global variable )

enter image description here

Also, I tried object.traverse in render function and I got the same error (traverse got replaced with position in error).

Please help. Thanks in advance.

Following is where I'm loading the obj and copying it to companion.

var mtlLoader = new THREE.MTLLoader();

mtlLoader.setPath( 'obj/' );
mtlLoader.load( 'satellite.mtl', function( materials ) {

    materials.preload();

    var objLoader = new THREE.OBJLoader();
    objLoader.setMaterials( materials );
    objLoader.setPath( 'obj/' );
    objLoader.load( 'satellite.obj', function( object ) {

        object.position.z = 300;
        object.scale.set( 0.25, 0.25, 0.25 );
        object.rotation.y = Math.PI;

        object.traverse( function( child ) { 

            if ( child instanceof THREE.Mesh ) { 

                child.castShadow = true;
                if ( child.material !== undefined ) child.material.side = THREE.DoubleSide;

            }
        });

        companion = object;
        scene.add( object );
    });

});

Upvotes: 0

Views: 716

Answers (1)

gaitat
gaitat

Reputation: 12632

You can use the following pattern:

var parent = new THREE.Group();
scene.add( parent );

In your load code replace

// companion = object;
// scene.add( object )
// with
parent.add( object ); // will add the object to the parent but also to the scene

then in your animate() function you can do something like:

parent.position.x = ....

Upvotes: 2

Related Questions