animation.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /* creates an animation of a number running either from 0 to max
  2. * or from max to 0
  3. */
  4. class Animation {
  5. /* by default the animation rests at 0 and is not running */
  6. constructor(max) {
  7. /* shows where the animation currently is */
  8. this.timer = 0;
  9. /* animation's max value */
  10. this.max = max;
  11. /* shows if the animation is moving positively (from 0 to max)
  12. * or negatively (from max to 0)
  13. * this also helps determine if the animation is resting or running
  14. */
  15. this.positive = false;
  16. } /* constructor */
  17. /* if animation is running, move one step
  18. * returns true if animation moved to a new value
  19. * returns false if nothing changed
  20. */
  21. update() {
  22. /* animation is running */
  23. if (this.is_running()) {
  24. /* advance animation (either positively or negatively) */
  25. this.timer += this.positive ? 1 : -1;
  26. return true;
  27. } /* animation running */
  28. /* animation is not running */
  29. return false;
  30. } /* update */
  31. /* returns true if animation is currently running
  32. * (either positively or negatively)
  33. * returns false otherwise
  34. */
  35. is_running() {
  36. return (this.timer < this.max && this.positive)
  37. || (this.timer > 0 && !this.positive);
  38. } /* is running */
  39. /* change animation's direction between positive/negative */
  40. flip() { this.positive = !this.positive; };
  41. /* returns the interpolated value of distance based
  42. * on animation's timer and max value
  43. * returns 0 when animation is on starting position
  44. * 0.5 when animation is half-way done
  45. * 1.0 when animation is at the end value
  46. */
  47. interpolate(distance) {
  48. return distance *this.timer /this.max;
  49. }
  50. /* flips the animation, but only if it is not running */
  51. start() {
  52. if (!this.is_running()) {
  53. this.flip();
  54. }
  55. } /* start */
  56. /* change maximum value */
  57. set_max(max) {
  58. /* change value */
  59. this.max = max;
  60. /* make sure pointer is not pointing outside of range
  61. * if max would cause the animation to stop
  62. * move it one step below it, so the animation updates
  63. * one last time
  64. */
  65. if (this.timer > max) {
  66. this.timer = max -1;
  67. }
  68. } /* set max */
  69. } /* class Animation */