Thursday, December 17, 2020

Dissecting glTF loading example

Main items functions are


createCamera

createControls

createLights

loadModels

createRenderer


Camera created is PerspectiveCAmera 


camera = new THREE.PerspectiveCamera(35, container.clientWidth / container.clientHeight, 1, 100);

camera.position.set(-1.5, 1.5, 6.5);



Control Created is simple Orbit Controls 

controls = new THREE.OrbitControls(camera, container);


Model loading is done using below steps. These are gLTF models

const loader = new THREE.GLTFLoader();


const parrotPosition = new THREE.Vector3(0, 0, 2.5);

loader.load('models/Parrot.glb', gltf => onLoad(gltf, parrotPosition), onProgress, onError);


const flamingoPosition = new THREE.Vector3(7.5, 0, -10);

loader.load('models/Flamingo.glb', gltf => onLoad(gltf, flamingoPosition), onProgress, onError);


const storkPosition = new THREE.Vector3(0, -2.5, -10);

loader.load('models/Stork.glb', gltf => onLoad(gltf, storkPosition), onProgress, onError);


Once the models are initiated for loading, there are three call backs, 

One is on Progress, on Load, on Error.


The gltf object come inside the onLoad method. 


Below are the main things done inside the onLoad method. 


1. The model object is inside the scene object. This is extracted. 


const model = gltf.scene.children[0];

model.position.copy(position) 


Once the model is loaded, its position is set by the above statement. The position is passed in from the application layer. 

Once the models position is set, now we need to mix the animations. This is done by the below statements 


const mixer = new THREE.AnimationMixer(model);

mixers.push(mixer);


mixers is an array which contains all the mixer instances. In the update loop, each of these mixers are to be given the update cycle, which is like this below .


function update() {


  const delta = clock.getDelta();

  for (const mixer of mixers) {

    mixer.update(delta);

  }

}



Now the mixer to be added with the animation 


const action = mixer.clipAction(animation);

action.play();



Now the model can be set in the scene


scene.add(model);


References:

 

No comments:

Post a Comment