【问题标题】:How can I loop a GLTF animation in three.js with random intervals?如何以随机间隔在 three.js 中循环播放 GLTF 动画?
【发布时间】:2021-09-25 22:10:46
【问题描述】:

我正在尝试使用 Three.js 创建游戏,我想问是否有办法为 GLFT 模型设置动画,但我想使用随机间隔而不是动画循环。就我而言,游戏是关于照顾青蛙的(但我很酷,所以我把它拼成了 phrogs),作为一个空闲动画,我希望青蛙随机发出叫声。在进一步的开发中,我还想为运动、进食等添加随机播放动画,但现在我只需要呱呱叫的动画。 以下是加载模型并为其设置动画的代码:

const basePhrog = new GLTFLoader()
var obj
basePhrog.load('assets/models/Phrogs/base phrog/phrog.gltf', function (gltf) {
  mixer = new THREE.AnimationMixer(gltf.scene)
  obj = gltf.scene
  var action = mixer.clipAction(gltf.animations[0])
  scene.add(gltf.scene)
  action.play()
})

我的动画循环如下所示:

function animate () {
  requestAnimationFrame(animate)
  var delta = clock.getDelta()
  if (mixer) mixer.update(delta)
  renderer.render(scene, camera)
}
animate()

希望您能提供帮助,感谢您的任何建议!

【问题讨论】:

    标签: javascript animation three.js gltf


    【解决方案1】:

    glTF 文件提供一个动画(或 Three.js 术语中的 THREE.AnimationClip),该剪辑的播放由 THREE.AnimationAction 实例管理。您示例中的代码将立即开始播放该动画,并永远循环播放,但 AnimationAction 不必以这种方式使用。

    相反,您可以等待并以随机间隔播放动作:

    var action = mixer.clipAction( animation );
    action.loop = THREE.LoopOnce;
    
    // Play animation randomly every 1-10s.
    setInterval(() => {
      action
        .reset()
        .play();
    }, Math.random() * 9000 + 1000);
    

    无论动画是否在任何给定时间播放,您都可以像现在一样继续更新 AnimationMixer。

    如果您稍后尝试在同一个对象上播放多个动画,一些用于在两个动画之间转换的 API 可能会有所帮助,请参阅 animation / skinning / morph 示例。

    【讨论】:

    • 您好,我在加载部分将您的代码粘贴到我的代码中,现在我收到“动画未定义”的错误,这是正常的吗?会不会是我的 js 位于导致此错误的 HTML 的单独文件中?
    • 对于您的代码 sn-p 以上animation 将替换为gltf.animations[0]。它需要是一个 AnimationClip 实例。
    猜你喜欢
    • 2016-03-01
    • 2016-12-29
    • 2020-06-27
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多