SpriteFrames.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. class SpriteAnimation
  2. {
  3. constructor(name = "default", p5Image, rows, cols, indices)
  4. {
  5. this.name = name;
  6. this.fullP5Image = p5Image;
  7. this.rows = rows;
  8. this.columns = cols;
  9. this.indices = indices;
  10. this.numFrames = this.indices.length;
  11. this.frameTime = 1 / 24;
  12. this.frames = [];
  13. for (let i = 0; i < this.numFrames; i++)
  14. {
  15. this.frames.push(this.makeFrame(i));
  16. }
  17. }
  18. setFrameTime(time)
  19. {
  20. this.frameTime = time;
  21. }
  22. setFPS(fps)
  23. {
  24. this.frameTime = 1 / fps;
  25. }
  26. getFrame(idx)
  27. {
  28. if (idx < this.numFrames)
  29. return this.frames[idx];
  30. return null;
  31. }
  32. getFrameTime()
  33. {
  34. return this.frameTime;
  35. }
  36. getNumFrames()
  37. {
  38. return this.numFrames;
  39. }
  40. makeFrame(idx)
  41. {
  42. let r = int(this.indices[idx] / this.columns);
  43. let c = this.indices[idx] % this.columns;
  44. let w = this.fullP5Image.width / this.columns;
  45. let h = this.fullP5Image.height / this.rows;
  46. let x = c * w;
  47. let y = r * h;
  48. return this.fullP5Image.get(x, y, w, h);
  49. }
  50. }
  51. class SpriteFrames
  52. {
  53. constructor()
  54. {
  55. this.animations = [];
  56. this.numAnimations = 0;
  57. }
  58. getAnimationByIndex(idx)
  59. {
  60. if (idx < this.numAnimations) return this.animations[idx];
  61. return null;
  62. }
  63. getAnimationByName(name)
  64. {
  65. for (let i = 0; this.numAnimations; i++)
  66. {
  67. if (this.animations[i].name == name)
  68. {
  69. return this.animations[i];
  70. }
  71. }
  72. return null;
  73. }
  74. getAnimationIndexByName(name)
  75. {
  76. for (let i = 0; this.numAnimations; i++)
  77. {
  78. if (this.animations[i].name == name)
  79. {
  80. return i;
  81. }
  82. }
  83. return null;
  84. }
  85. addAnimation(name, p5Image, rows, cols, indices)
  86. {
  87. this.animations.push(new SpriteAnimation(name, p5Image, rows, cols, indices));
  88. this.numAnimations++;
  89. }
  90. }