You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

stepper.js.flow 1.3 KiB

3 vuotta sitten
123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /* @flow */
  2. // stepper is used a lot. Saves allocation to return the same array wrapper.
  3. // This is fine and danger-free against mutations because the callsite
  4. // immediately destructures it and gets the numbers inside without passing the
  5. // array reference around.
  6. let reusedTuple: [number, number] = [0, 0];
  7. export default function stepper(
  8. secondPerFrame: number,
  9. x: number,
  10. v: number,
  11. destX: number,
  12. k: number,
  13. b: number,
  14. precision: number): [number, number] {
  15. // Spring stiffness, in kg / s^2
  16. // for animations, destX is really spring length (spring at rest). initial
  17. // position is considered as the stretched/compressed position of a spring
  18. const Fspring = -k * (x - destX);
  19. // Damping, in kg / s
  20. const Fdamper = -b * v;
  21. // usually we put mass here, but for animation purposes, specifying mass is a
  22. // bit redundant. you could simply adjust k and b accordingly
  23. // let a = (Fspring + Fdamper) / mass;
  24. const a = Fspring + Fdamper;
  25. const newV = v + a * secondPerFrame;
  26. const newX = x + newV * secondPerFrame;
  27. if (Math.abs(newV) < precision && Math.abs(newX - destX) < precision) {
  28. reusedTuple[0] = destX;
  29. reusedTuple[1] = 0;
  30. return reusedTuple;
  31. }
  32. reusedTuple[0] = newX;
  33. reusedTuple[1] = newV;
  34. return reusedTuple;
  35. }