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.2KB

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