Reputation: 25
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)
Upvotes: 1
Views: 3904
Reputation: 900
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);
}
Upvotes: 6