Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. // these are your keyframes, in a format compatible with THREE.Vector3.
  2. // Please note that the time `t` is expected in milliseconds here.
  3. // (must have properties named x, y and z - otherwise the copy below doesn't work)
  4. const keyframes = [
  5. {t: 0, x: 318, y: 24, z: 3},
  6. {t: 25, x: 318, y: 24, z: 3},
  7. // ... and so on
  8. ];
  9.  
  10. // find a pair of keyframes [a, b] such that `a.t < t` and `b.t > t`.
  11. // In other words, find the previous and next keyframe given the
  12. // specific time `t`. If no previous or next keyframes is found, null
  13. // is returned instead.
  14. function findNearestKeyframes(t) {
  15. let prevKeyframe = null;
  16. for (let i = 0; i < keyframes.length; i++) {
  17. if (keyframes[i].t > t) {
  18. return [prevKeyframe, keyframes[i]];
  19. }
  20. prevKeyframe = keyframes[i];
  21. }
  22.  
  23. return [prevKeyframe, null];
  24. }
  25.  
  26. const tmpV3 = new THREE.Vector3();
  27.  
  28. function loop(t) {
  29. const [prevKeyframe, nextKeyframe] = findNearestKeyframes(t);
  30.  
  31. // (...not handling cases where there is no prev or next here)
  32.  
  33. // compute the progress of time between the two keyframes
  34. // (0 when t === prevKeyframe.t and 1 when t === nextKeyframe.t)
  35. let progress = (t - prevKeyframe.t) / (nextKeyframe.t - prevKeyframe.t);
  36.  
  37. // copy position from previous keyframe, and interpolate towards the
  38. // next keyframe linearly
  39. tmpV3.copy(nextKeyframe);
  40. someObject.position
  41. .copy(prevKeyframe)
  42. .lerp(tmpV3, progress);
  43.  
  44. // (...render scene)
  45.  
  46. requestAnimationFrame(loop);
  47. }
  48.  
  49. // start the animation-loop
  50. requestAnimationFrame(loop);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement