I'm trying to understand how three.js accesses a loaded model. This is the example I'm working on to try and understand:
I load a model, a simple Blender cube with a texture and a spotlight. I declare 'box' before the loader:
var box;
// load in geometry and textures
var loader = new THREE.JSONLoader();
loader.load('../models/two textures on cube 03.js', function (geometry, material)
{
box = new THREE.Mesh(geometry, material[2]);
//position, scale
box.position.set (0,0,0);
box.rotation.set (0,-1.2,0);
box.scale.set (2,2,2);
box.receiveShadow = true;
scene.add(box);
// add spotlight for the shadows
var spotLight = new THREE.SpotLight( 0xffffff );
spotLight.position.set( -10, 14, 14 );
spotLight.target = box;
spotLight.castShadow = true;
scene.add( spotLight );
}, '../models');
This works. But if I move the spotlight coding outside of the loader brackets (after it) the spotlight doesn't work, even though I've declared 'box' outside of the brackets.
I know that if I add the spotlight to the render function in this way:
if (box) {
//all spotlight coding added in here, exactly as used above
}
then this works. But I don't know why.
I also know that if I don't add box directly to the scene but place the box within an Object3D which is declared before the loader, then I can add the spotlight after the loader and target the spotlight at the Object3D and it works.
Why does the spotlight 'see' the Object3D declared before the loader but doesn't see 'var box'? And why can it 'see' the box if I use that if statement within the render function? Is it something to do with how long it takes to complete the loader function?
Thanks for any help.
The loading of the model is asynchronous so you are not sure that after the call has executed the model is really loaded. So what you should have is:
var loader = new THREE.JSONLoader();
loader.onLoadComplete = function () {
// here you know that the model has loaded
scene.add (box);
}
loader.load ...
The spotlight code should be totally separate and not mixed with the loading code.
You can find more about the loader.onLoad*
methods at http://threejs.org/docs/index.html#Reference/Loaders/Loader