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

时间:2018-04-20 05:28:45

标签: javascript three.js

我们假设我在position.x = 0处有一个形状,我想在渲染循环中将其平滑地设置为position.x = 2.435。我该怎么做呢?

2 个答案:

答案 0 :(得分:2)

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

var targetPositionX = 2.435;

然后在渲染循环中,创建一个if语句,检查对象的X position是否小于targetPositionX。如果是,它将添加一个增量(您可以根据您希望它移动的速度更改)到对象的X position。当对象的X位置变得大于或等于targetPositionX时,它将停止移动。

这样的事情:

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,我建议你阅读。

答案 1 :(得分:1)

您可以使用三个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);
};
相关问题