我有一个数据,以毫秒为单位的时间和当时对象的位置(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 次,但如果我的场景很重,我想帧速率会下降。无论如何这都不能解决我的问题。
我正在寻找一个不依赖于浏览器当前帧速率的强大解决方案。 请帮忙。
最佳答案
有几种方法可以解决这个问题,无论有没有库。
你是对的,它并不像计算动画循环的滴答数那么简单,因为不能保证它每 1/60 秒发生一次。但是动画帧回调(下面代码中的循环
)将获取作为第一个参数传递的时间戳,可用于计算动画进度。
所以,在 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 左右的关键帧时,您可以根据以下条件从更高的索引开始预先计算的信息。您可能可以使用许多其他算法和结构来加速它。
关于javascript - 将动画时序与数据同步(ThreeJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47015110/