AnimatedSprite2D.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. class AnimatedSprite2D extends Sprite2D
  2. {
  3. constructor(name, p5Image, spriteFrames)
  4. {
  5. super(name, p5Image);
  6. this.spriteFrames = spriteFrames;
  7. this.playing = false;
  8. this.frame = 0;
  9. this.currentAnimation = 0;
  10. this.timeSinceLastFrame = 0;
  11. }
  12. // Setters
  13. setCurrentAnimationByIndex(idx)
  14. {
  15. if (idx < this.spriteFrames.numAnimations)
  16. this.currentAnimation = idx;
  17. else this.currentAnimation = null;
  18. this.frame = 0;
  19. this.timeSinceLastFrame = 0;
  20. }
  21. setCurrentAnimationByName(name)
  22. {
  23. this.currentAnimation = this.spriteFrames.getAnimationIndexByName(name);
  24. this.frame = 0;
  25. this.timeSinceLastFrame = 0;
  26. }
  27. setCurrentFrameTime(time)
  28. {
  29. this.getCurrentAnimation().setFrameTime(time);
  30. }
  31. setCurrentFPS(fps)
  32. {
  33. this.getCurrentAnimation().setFPS(fps);
  34. }
  35. // Getters
  36. getAnimationByIndex(idx)
  37. {
  38. return this.spriteFrames.getAnimationByIndex(idx);
  39. }
  40. getCurrentAnimation()
  41. {
  42. return this.spriteFrames.getAnimationByIndex(this.currentAnimation);
  43. }
  44. getCurrentFrame()
  45. {
  46. return this.getCurrentAnimation().getFrame(this.frame);
  47. }
  48. getCurrentFrameTime()
  49. {
  50. return this.getCurrentAnimation().getFrameTime();
  51. }
  52. getCurrentNumFrames()
  53. {
  54. return this.getCurrentAnimation().getNumFrames();
  55. }
  56. // Methods
  57. play()
  58. {
  59. this.playing = true;
  60. }
  61. stop()
  62. {
  63. this.playing = false;
  64. }
  65. isPlaying()
  66. {
  67. return this.playing;
  68. }
  69. update(delta)
  70. {
  71. if (this.playing)
  72. {
  73. this.timeSinceLastFrame += delta;
  74. if (this.timeSinceLastFrame >= this.getCurrentFrameTime())
  75. {
  76. this.frame = (this.frame + 1) % this.getCurrentNumFrames();
  77. this.timeSinceLastFrame = 0;
  78. }
  79. }
  80. this.P5Image = this.getCurrentFrame();
  81. this._update(delta);
  82. for (let i = 0; i < this.children.length; i++)
  83. this.children[i].update(delta);
  84. }
  85. }