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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import Player from './entities/Player.js';
  2. import structures from './structures.js';
  3. export default class Level {
  4. constructor(canvas) {
  5. this.step = 1 / 120;
  6. this.stepLimit = 2;
  7. this.canvas = canvas;
  8. this.ctx = canvas.getContext("2d");
  9. this.lastTime = null;
  10. this.raf = null;
  11. this.timeAcc = 0;
  12. this.entities = [];
  13. this.evts = [];
  14. this.structure = structures.floor(2, 2, 1);
  15. }
  16. spawn(ent, x, y) {
  17. ent.bounds.pos.set(x, y);
  18. this.entities.push(ent);
  19. ent.init();
  20. }
  21. physics(dt) {
  22. this.entities.forEach(ent =>
  23. ent.update(dt));
  24. this.entities.forEach(ent => {
  25. ent.bounds.pos.x += ent.velocity.x * dt;
  26. ent.bounds.pos.y += ent.velocity.y * dt;
  27. });
  28. }
  29. draw() {
  30. this.ctx.resetTransform();
  31. this.ctx.beginPath();
  32. this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  33. this.entities.forEach(ent => ent.draw(this.ctx));
  34. this.structure.draw(this.ctx);
  35. }
  36. update(time) {
  37. if (this.lastTime != null) {
  38. let dt = (time - this.lastTime) / 1000;
  39. this.timeAcc += dt;
  40. if (this.timeAcc > this.stepLimit) {
  41. console.warn(
  42. "Attempt to simulate "+this.timeAcc.toFixed(2)+" "+
  43. "seconds, which is over the limit ("+this.stepLimit+"s). "+
  44. "Resetting accumulator.");
  45. this.timeAcc = dt;
  46. }
  47. let nticks = 0;
  48. while (this.timeAcc >= this.step) {
  49. nticks += 1;
  50. this.physics(this.step);
  51. this.timeAcc -= this.step;
  52. }
  53. this.draw();
  54. }
  55. this.lastTime = time;
  56. this.raf = requestAnimationFrame(this.update.bind(this));
  57. }
  58. start() {
  59. if (this.raf == null) {
  60. this.lastTime = null;
  61. this.update();
  62. console.log("Started.");
  63. }
  64. }
  65. stop() {
  66. if (this.raf != null) {
  67. cancelAnimationFrame(this.raf);
  68. this.raf = null;
  69. console.log("Stopped.");
  70. }
  71. }
  72. }