Your scene is ready. Your model is ready. Now it’s time to load it in and make it come alive!
In this milestone, you'll use the GLTFLoader
to import your .glb
model into the scene and initialize its animations.
GLTFLoader
to load your .glb
modelAnimationMixer
Open app.js
and update your script with the following additions. This will load your model and prepare its animations.
let dog;
let mixer;
let actions = {};
let currentAction;
// Create GLTF Loader
const loader = new GLTFLoader();
// Load the model
loader.load(
"animated_dog_shiba_inu.glb",
function (gltf) {
dog = gltf.scene;
dog.position.set(0, 0, 0);
scene.add(dog);
// Setup animations
mixer = new THREE.AnimationMixer(dog);
if (gltf.animations && gltf.animations.length > 0) {
// Store all actions
gltf.animations.forEach((clip, index) => {
actions[`clip${index}`] = mixer.clipAction(clip);
});
}
// Play initial animation
currentAction = actions["clip3"];
currentAction.play();
},
function (xhr) {
console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
},
function (error) {
console.error("Error loading model:", error);
}
);
To play animations smoothly, add this line to your render loop:
if (mixer) mixer.update(delta);
Your updated loop should look like this:
// Update render loop to include animation mixer
const clock = new THREE.Clock();
const reRender3D = () => {
requestAnimationFrame(reRender3D);
renderer.render(scene, camera);
const delta = clock.getDelta();
if (mixer) mixer.update(delta);
};
reRender3D();