我正在尝试使用模型查看器播放动画一次

I am trying to play animation once with Model Viewer

提问人:Blue Li 提问时间:6/18/2023 更新时间:6/18/2023 访问量:195

问:

我正在尝试制作一个多动作 GLB 文件来播放每个动画动作一次。

我的第一次尝试是使用代码,它在播放后成功停止了初始动画。我用第二个动作名称更新了 attr animation-name。它触发 play(),但是在动画结束后它不会停止。

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();
});

我的第二次尝试

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();
});

这是容器

<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>

我不明白为什么modelViewer.play({ repetitions: 1 });属性更改后无法工作 或者关于如何让我的代码在这种情况下工作有什么更好的主意吗?

谢谢

GLTF 模型查看器

评论


答: 暂无答案