I am trying to make a multiple actions GLB file to play each animation action once.
My first attempt is to use code, it successfully stops the initial animation after it is played. I update the attr animation-name with the second action name. It triggers play() however it won't stop after the animation is ended.
const modelViewer = document.querySelector('#home-model-2');
const playOnce = () => {
modelViewer.removeEventListener('animation-finish', playOnce);
modelViewer.pause();
modelViewer.currentTime = 0;
};
const play = () => {
modelViewer.play({ repetitions: 1 });
modelViewer.addEventListener('animation-finish', playOnce);
};
const onAnimationNameChange = () => {
play();
};
modelViewer.addEventListener('load', () => {
// Create a new MutationObserver instance
const observer = new MutationObserver((mutationsList) => {
for (const mutation of mutationsList) {
if (mutation.type === 'attributes' && mutation.attributeName === 'animation-name') {
onAnimationNameChange();
}
}
});
// Start observing changes to the attributes of the modelViewer element
observer.observe(modelViewer, { attributes: true });
// Initial play
play();
});
My second attempt
const modelViewer = document.querySelector('#home-model-2');
const playOnce = () => {
modelViewer.removeEventListener('animation-finish', playOnce);
modelViewer.pause();
modelViewer.currentTime = 0;
};
const play = () => {
modelViewer.play({ repetitions: 1 });
modelViewer.addEventListener('animation-finish', playOnce);
};
const onAnimationNameChange = () => {
modelViewer.removeEventListener('animation-finish', playOnce);
play();
};
modelViewer.addEventListener('load', () => {
const observer = new MutationObserver((mutationsList) => {
for (const mutation of mutationsList) {
if (mutation.type === 'attributes' && mutation.attributeName === 'animation-name') {
onAnimationNameChange();
}
}
});
observer.observe(modelViewer, { attributes: true });
play();
});
This is the container
<model-viewer id="home-model-2" src="//xxx.glb" ar-status="not-presenting" touch-action="none" shadow-intensity="0.3" autoplay="" exposure="1" shadow-softness="1" camera-orbit="8.742deg 83.8deg 2.011m" field-of-view="30deg" camera-target="-0.4517m 0.39m 0.1061m" animation-name="s2">
</model-viewer>
I dont understand why modelViewer.play({ repetitions: 1 }); could not work after the attributes is changed or Any better idea on how to make my code work in this case?
Thanks