pickup_spawner.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /* generates pickups every X time */
  2. class PickupSpawner {
  3. /* initialize */
  4. constructor(ground, spawn_speed = 60, limit = 5) {
  5. /* container to keep all pickups with the collectors */
  6. this.container = ground;
  7. /* data */
  8. this.array = [];
  9. this.limit = limit;
  10. this.sound = new Audio("audio/crystal_pickup.mp3");
  11. this.spawn_speed = spawn_speed;
  12. /* animation to spawn new crystal */
  13. this.anim_spawn = new Animation(this.spawn_speed);
  14. this.anim_spawn.start();
  15. } /* constructor */
  16. /* update animation, spawn new crystals */
  17. update() {
  18. /* update animation */
  19. if (this.anim_spawn.update()) {
  20. /* animation stopped */
  21. if (!this.anim_spawn.is_running()) {
  22. /* there is space to create new crystal */
  23. if ( this.array.length < this.limit ) {
  24. /* create new crystal */
  25. let crystal = new PIXI.Sprite(
  26. loader.resources["images/crystal.png"].texture );
  27. crystal.anchor = {x:0.5, y:0.5};
  28. crystal.x = crystal.width*2 +Math.floor( Math.random() *(width -crystal.width*4) );
  29. crystal.y = crystal.height*2 +Math.floor( Math.random() *(height -crystal.height*4) );
  30. /* add crystal to array */
  31. this.array.push(crystal);
  32. /* place crystal in container, based on its bottom Y */
  33. let position = this.container.children.length;
  34. let y = crystal.y +crystal.height;
  35. for (let i = 0; i < this.container.children.length; i++) {
  36. let child = this.container.children[i];
  37. let y2 = child.y +child.height;
  38. if (y < y2) {
  39. position = i;
  40. break;
  41. }
  42. }
  43. this.container.addChildAt(crystal, position);
  44. } /* space to create crystal */
  45. /* restart animation */
  46. this.anim_spawn.timer = 0;
  47. } /* animation stopped */
  48. } /* animation updated */
  49. } /* update */
  50. /* user clicked on a point on the screen,
  51. * if they touched a crystal, pick it up and return its index
  52. * else return -1
  53. */
  54. collect(p) {
  55. /* for every crystal */
  56. for (let i = 0; i < this.array.length; i++) {
  57. /* user touched crystal */
  58. if (this.array[i].containsPoint(p)) {
  59. /* play sound */
  60. if (!muted) {
  61. this.sound.play();
  62. }
  63. /* return crystal's index */
  64. return i;
  65. } /* user touched crystal */
  66. } /* for every crystal */
  67. /* no crystal was touched */
  68. return -1;
  69. } /* contains */
  70. /* change speed of spawning crystals */
  71. set_speed(spd) {
  72. this.anim_spawn.max = spd;
  73. this.anim_spawn.timer = 0;
  74. }
  75. } /* PickupSpawner */