我有一个数据,以毫秒为单位的时间和当时对象的位置(x,y,z)。
msec |poz_x |poz_y |poz_z
------------------------------
0 |318 |24 |3
25 |318 |24 |3
49 |318 |23 |3
70 |318 |22 |2
91 |318 |22 |2
113 |318 |21 |1
136 |318 |21 |1
e.t.c
问题是实际和下一个数据之间的时差变化(来自传感器)。
我正在寻找一种实时制作动画的方法。
如果在我的数据中我有60秒的信息,则需要在60秒内在浏览器中设置动画。
我已经读过requestAnimationFrame( animate );
将每秒重复60次这个功能,但如果我的场景很重,我想帧速率会下降。无论如何,这无法解决我的问题。
我正在寻找一种不依赖于浏览器当前帧率的强大解决方案。 请帮忙。
答案 0 :(得分:1)
有或没有库,有几种方法可以解决这个问题。
你是对的,它不像计算动画循环的滴答数那么简单,因为不能保证它每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);
编辑:要解决有关优化findNearestKeyframes
功能的评论中的一个问题:
一旦你了解了几千个关键帧,那么优化它可能是有意义的,是的。对于像几百的东西,它不值得努力(我将其归类为过早优化)。
要进行优化,您可以创建索引表,以便跳过数组的不相关部分。例如,您可以将索引存储在关键帧数组中,每10秒开始一次或类似,这样 - 当您在t = 12.328s周围搜索关键帧时,您可以从更高的索引开始基于预先计算的信息。可能有很多其他算法和结构可以用来加速它。