比方说,我有一个形状在position.x = 0
的位置,我想在渲染循环中平滑地将其动画化到position.x = 2.435
。我应该怎么做呢?
比方说,我有一个形状在position.x = 0
的位置,我想在渲染循环中平滑地将其动画化到position.x = 2.435
。我应该怎么做呢?
你可以使用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);
};
将目标位置设为变量(在渲染循环之外):
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,我建议你仔细研究一下它。