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.

Level.js 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import structures from "./structures.js";
  2. export default class Level {
  3. constructor(canvas) {
  4. this.canvas = canvas;
  5. this.ctx = canvas.getContext("2d");
  6. this.lastTime = null;
  7. this.raf = null;
  8. this.entities = [];
  9. this.colliders = [];
  10. this.structures = [];
  11. this.evts = [];
  12. }
  13. spawnEntity(ent, x, y) {
  14. ent.bounds.pos.set(x, y);
  15. this.entities.push(ent);
  16. if (ent.has("collider"))
  17. this.colliders.push(ent);
  18. ent._init();
  19. }
  20. spawnStructure(structure, x, y) {
  21. structure.bounds.pos.set(x, y);
  22. this.structures.push(structure);
  23. structure.init();
  24. }
  25. physics(dt) {
  26. this.entities.forEach(ent =>
  27. ent._update(dt));
  28. this.entities.forEach(ent =>
  29. ent._postUpdate(dt));
  30. // Collide with structures
  31. this.structures.forEach(s => {
  32. if (!s.attrs.collides)
  33. return;
  34. this.colliders.forEach(ent => {
  35. let bounds = s.collidesWith(ent.bounds);
  36. if (!bounds)
  37. return;
  38. ent.t.collider.collideStructure(bounds);
  39. });
  40. });
  41. // Collide with entities
  42. this.colliders.forEach(ent => {
  43. this.colliders.forEach(ent2 => {
  44. if (ent === ent2 || !ent.bounds.intersects(ent2.bounds))
  45. return;
  46. ent.t.collider.collideEntity(ent2);
  47. });
  48. });
  49. }
  50. draw() {
  51. this.ctx.resetTransform();
  52. this.ctx.beginPath();
  53. this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  54. this.entities.forEach(ent => ent.draw(this.ctx));
  55. this.structures.forEach(struct => struct.draw(this.ctx));
  56. }
  57. update(time) {
  58. if (this.lastTime != null) {
  59. let dt = (time - this.lastTime) / 1000;
  60. this.physics(dt);
  61. this.draw();
  62. }
  63. this.lastTime = time;
  64. this.raf = requestAnimationFrame(this.update.bind(this));
  65. }
  66. start() {
  67. if (this.raf == null) {
  68. this.lastTime = null;
  69. this.update();
  70. console.log("Started.");
  71. }
  72. }
  73. stop() {
  74. if (this.raf != null) {
  75. cancelAnimationFrame(this.raf);
  76. this.raf = null;
  77. console.log("Stopped.");
  78. }
  79. }
  80. }