I am trying to manipulate (e.g. change position, scale, rotation) an object loaded using OBJLoader in Three.js. While this is easy to do so once, I cannot work out how to do this when I want e.g. during the animate loop, or anywhere outside of the initial load callback.
Here is my code:
function loadObj( path, name )
{
var obj;
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath( path );
mtlLoader.load( name+".mtl", function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.setPath( path );
objLoader.load( name+".obj", function( object ) {
obj = object;
obj.position.x = 20;
scene.add( obj );
});
});
return obj;
}
var myObj = loadObj( "assets/", "test" );
myObj.position.y = 20;
The key points to note here are:
- I can load it and manipulate it within the loop fine, and no errors are raised;
- If I do the above, I'll get an error on the last line, which states:
Cannot read property 'position' of undefined
. - This error remains if I define
obj
outside the function (as a global), and then reference it accordingly.
I've tried similar code with the JSON loader, to the same results (I am able to manipulate it within the load, but not afterwards).