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 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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.minFPS = 10;
  9. this.entities = [];
  10. this.colliders = [];
  11. this.structures = [];
  12. this.evts = [];
  13. }
  14. spawnEntity(ent, x, y) {
  15. ent.bounds.pos.set(x, y);
  16. this.entities.push(ent);
  17. if (ent.has("collider"))
  18. this.colliders.push(ent);
  19. ent._init();
  20. }
  21. spawnStructure(structure, x, y) {
  22. structure.bounds.pos.set(x, y);
  23. this.structures.push(structure);
  24. structure.init();
  25. }
  26. physics(dt) {
  27. this.entities.forEach(ent =>
  28. ent._update(dt));
  29. this.entities.forEach(ent =>
  30. ent._postUpdate(dt));
  31. // Collide with structures
  32. this.structures.forEach(s => {
  33. if (!s.attrs.wall && !s.attrs.platform)
  34. return;
  35. this.colliders.forEach(ent => {
  36. let bounds = s.collidesWith(ent.bounds);
  37. if (!bounds)
  38. return;
  39. ent.t.collider.collideStructure(s, bounds);
  40. });
  41. });
  42. // Collide with entities
  43. this.colliders.forEach(ent => {
  44. this.colliders.forEach(ent2 => {
  45. if (ent === ent2 || !ent.bounds.intersects(ent2.bounds))
  46. return;
  47. ent.t.collider.collideEntity(ent2);
  48. });
  49. });
  50. }
  51. draw() {
  52. this.ctx.resetTransform();
  53. this.ctx.beginPath();
  54. this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  55. this.entities.forEach(ent => ent.draw(this.ctx));
  56. this.structures.forEach(struct => struct.draw(this.ctx));
  57. }
  58. update(time) {
  59. if (this.lastTime != null) {
  60. let dt = (time - this.lastTime) / 1000;
  61. if (1 / dt > this.minFPS) {
  62. this.physics(dt);
  63. } else {
  64. console.log(
  65. "Too long between updates ("+dt.toFixed(2)+"s, "+
  66. (1 / dt).toFixed(2)+"FPS). Skipping.");
  67. }
  68. this.draw();
  69. }
  70. this.lastTime = time;
  71. this.raf = requestAnimationFrame(this.update.bind(this));
  72. }
  73. start() {
  74. if (this.raf == null) {
  75. this.lastTime = null;
  76. this.update();
  77. console.log("Started.");
  78. }
  79. }
  80. stop() {
  81. if (this.raf != null) {
  82. cancelAnimationFrame(this.raf);
  83. this.raf = null;
  84. console.log("Stopped.");
  85. }
  86. }
  87. }