简体   繁体   中英

Three.js Accessing an object after it was loaded with GLTF Loader

In three.js with GLTF loader, is there a way to access an object to perform transformations after it was loaded

Doing this doesn't seem to work

gltf.scene.position.set(10,10,10)

Code:

function loadObject(){
    var loader = new THREE.GLTFLoader();

    loader.load('test.gltf',
        function ( gltf ) {
            scene.add( gltf.scene );

        },
        function ( xhr ) {
            //console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
        },
        function ( error ) {
            //console.log( 'An error happened' );
        }
    );
}

loadObject()

// Translate
gltf.scene.position.set(10,10,10)

Yes, there is. It's all about scoping and having the variables available to you throughout your app.

Check the source of this example - https://threejs.org/examples/webgl_loader_gltf.html

See how the variables are declared and then used throughout the code (line 54,55).

var container, stats, controls;
var camera, scene, renderer, light;

You also need to remember that the gltf model data won't be available until it's loaded, so you'll need to integrate a way to handle that too. I expect that the gltf model hasn't loaded by the time you are trying to set the position of it.

The LoadingManager is a good way to manage this - https://threejs.org/docs/#api/en/loaders/managers/LoadingManager

You could execute an init() method once all of your assets have loaded, for example.

Example for your scenario:

var model;

function loadObject(){
    var loader = new THREE.GLTFLoader();

    loader.load('test.gltf',
        function ( gltf ) {

            model = gltf;
            scene.add( model );

            init();

        },
        function ( xhr ) {
            //console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
        },
        function ( error ) {
            //console.log( 'An error happened' );
        }
    );
}

loadObject()

function init() {
    // Translate
    model.scene.position.set(10,10,10);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM