有几种方法可以解决这个问题,无论是否使用库。
你是对的,它并不像计算动画循环的滴答数那么简单,因为不能保证它每 1/60 秒发生一次。但是动画帧回调(下面代码中的loop)将获得一个时间戳作为第一个参数传递,该参数可用于计算动画进度。
所以,在 javascript 中,可能是这样的:
// these are your keyframes, in a format compatible with THREE.Vector3.
// Please note that the time `t` is expected in milliseconds here.
// (must have properties named x, y and z - otherwise the copy below doesn't work)
const keyframes = [
{t: 0, x: 318, y: 24, z: 3},
{t: 25, x: 318, y: 24, z: 3},
// ... and so on
];
// find a pair of keyframes [a, b] such that `a.t < t` and `b.t > t`.
// In other words, find the previous and next keyframe given the
// specific time `t`. If no previous or next keyframes is found, null
// is returned instead.
function findNearestKeyframes(t) {
let prevKeyframe = null;
for (let i = 0; i < keyframes.length; i++) {
if (keyframes[i].t > t) {
return [prevKeyframe, keyframes[i]];
}
prevKeyframe = keyframes[i];
}
return [prevKeyframe, null];
}
const tmpV3 = new THREE.Vector3();
function loop(t) {
const [prevKeyframe, nextKeyframe] = findNearestKeyframes(t);
// (...not handling cases where there is no prev or next here)
// compute the progress of time between the two keyframes
// (0 when t === prevKeyframe.t and 1 when t === nextKeyframe.t)
let progress = (t - prevKeyframe.t) / (nextKeyframe.t - prevKeyframe.t);
// copy position from previous keyframe, and interpolate towards the
// next keyframe linearly
tmpV3.copy(nextKeyframe);
someObject.position
.copy(prevKeyframe)
.lerp(tmpV3, progress);
// (...render scene)
requestAnimationFrame(loop);
}
// start the animation-loop
requestAnimationFrame(loop);
编辑:解决 cmets 关于优化 findNearestKeyframes-function 的一个问题:
一旦您获得了数千个关键帧,就可以稍微优化一下,是的。对于几百个这样的东西,不值得付出努力(我将其归类为过早的优化)。
为了优化,您可以创建一个索引表以跳过数组中不相关的部分。例如,您可以在每 10 秒或类似的开始时将索引存储在关键帧数组中,这样 - 当您在 t = 12.328s 附近搜索关键帧时,您可以从更高的索引开始预先计算的信息。您可能可以使用许多其他算法和结构来加速它。