Three.js从一个位置动画到另一个位置

4

比方说,我有一个形状在position.x = 0的位置,我想在渲染循环中平滑地将其动画化到position.x = 2.435。我应该怎么做呢?

2个回答

7

你可以使用THREE的AnimationMixer。下面的函数设置了动画,示例jsFiddle

const createMoveAnimation = ({ mesh, startPosition, endPosition }) => {
  mesh.userData.mixer = new AnimationMixer(mesh);
  let track = new VectorKeyframeTrack(
    '.position',
    [0, 1],
    [
      startPosition.x,
      startPosition.y,
      startPosition.z,
      endPosition.x,
      endPosition.y,
      endPosition.z,
    ]
  );
  const animationClip = new AnimationClip(null, 5, [track]);
  const animationAction = mesh.userData.mixer.clipAction(animationClip);
  animationAction.setLoop(LoopOnce);
  animationAction.play();
  mesh.userData.clock = new Clock();
  this.animationsObjects.push(mesh);
};

4

将目标位置设为变量(在渲染循环之外):

var targetPositionX = 2.435;

在你的渲染循环中,创建一个if语句来检查对象的 X位置 是否小于 目标X位置。如果是,则将增量添加到对象的 X位置(您可以根据需要调整移动速度)。当对象的X位置变得大于或等于 目标X位置 时,它将停止移动。

类似这样:

if (object.position.x <= targetPositionX) {
    object.position.x += 0.001; // You decide on the increment, higher value will mean the objects moves faster
}

这里是渲染循环的完整代码:
function loop(){

    // render the scene
    renderer.render(scene, camera);

    // Check the object's X position
    if (object.position.x <= targetPositionX) {
        object.position.x += 0.001; // You decide on the increment, higher value will mean the objects moves faster
    }

    // call the loop function again
    requestAnimationFrame(loop);
}

小提示

如果你需要更加详细或复杂的动画效果,建议使用 Three.js 的 Tween.js。它可以让动画制作更加简单,并且还可以为动画添加缓动函数。

你可以在这里找到它:

https://github.com/sole/tween.js

如果你正在学习 Three.js,我建议你仔细研究一下它。


我最初尝试了你的方法,但我想我知道我做错了什么。元素的起始点与增量(0.45356 += 0.001)不匹配,所以它一直错过。这个缓动库看起来很棒,我会试试的。谢谢你的信息! - Paul
@PaulB 是的,这就是为什么我使用小于/大于而不是等于,因为这意味着它必须完全等于目标才能停止,但是如果你的目标是4.5,而你每次增加0.451,你永远无法达到它!很高兴我能帮助到你,请接受我的答案,如果它对你有所帮助,这样其他人在未来就可以找到正确的解决方案 :) - JJ Gerrish

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接