Mapbox GL JS Animated GLTF Playground
Fri 05 March 2021There are lots of examples for getting started with Mapbox GL JS, and I've found it well worth my while to familiarize myself with them so I can copy/paste and hit the ground running.
One example I've found particularly useful is Add a 3D Model because it provides a lot of (what I consider to be) advanced code for using three.js to load and display 3D GLTF models into a Mapbox custom layer.
In addition to geometry and texture/material data, GLTFs may also contain embedded animations, which brings me to my GLTF Playground.
Curious how to make horses run or rockets blast off in @Mapbox ? Here's a playground to get you started: https://t.co/7gnEXforYZ pic.twitter.com/u3bgfLmogJ
— Darren Wiens (@dkwiens) March 6, 2021
The GLTF Playground demonstrates how to play animations for several models hosted in the three.js examples. If you take a look in the GLTF Playground source code or this gist, you may notice the use of a three.js AnimationMixer, which we can use to make sense of the animation(s) within the model.
The keys points for using the AnimationMixer are:
- Create the AnimationMixer:
loader.load(
model,
function (gltf) {
this.scene.add(gltf.scene);
mixer = new THREE.AnimationMixer(gltf.scene);
mixer.clipAction(gltf.animations[0]).setDuration(1).play();
}.bind(this)
);
- As time passes, update the mixer to a new frame in the animation:
if (mixer) {
const time = Date.now();
mixer.update((time - prevTime) * 0.001);
prevTime = time;
}
That's more or less it. You can adjust these values to play other animations contained within the model, modify the animation speed/direction, etc.
I'm always interested to see how you use 3D models and motion in web maps, so let me know on Twitter if you do!