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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import Player from './entities/Player';
  2. export default class Level {
  3. constructor(canvas) {
  4. this.step = 1 / 120;
  5. this.canvas = canvas;
  6. this.ctx = canvas.getContext("2d");
  7. this.lastTime = null;
  8. this.raf = null;
  9. this.timeAcc = 0;
  10. this.entities = [];
  11. }
  12. spawn(ent, x, y) {
  13. ent.bounds.pos.set(x, y);
  14. this.entities.push(ent);
  15. ent.init();
  16. }
  17. physics(dt) {
  18. this.entities.forEach(ent =>
  19. ent.update(dt));
  20. this.entities.forEach(ent => {
  21. ent.bounds.pos.x += ent.velocity.x * dt;
  22. ent.bounds.pos.y += ent.velocity.y * dt;
  23. });
  24. }
  25. draw() {
  26. this.canvas.width = window.innerWidth;
  27. this.canvas.height = window.innerHeight;
  28. this.entities.forEach(ent => ent.draw(this.ctx));
  29. }
  30. update(time) {
  31. if (this.lastTime != null) {
  32. let dt = (time - this.lastTime) / 1000;
  33. this.timeAcc += dt;
  34. while (this.timeAcc > this.step) {
  35. this.physics(this.step);
  36. this.timeAcc -= this.step;
  37. }
  38. this.draw();
  39. }
  40. this.lastTime = time;
  41. this.raf = requestAnimationFrame(time => this.update(time));
  42. }
  43. start() {
  44. this.stop();
  45. this.lastTime = null;
  46. this.update();
  47. }
  48. stop() {
  49. if (this.raf != null) {
  50. cancelAnimationFrame(this.raf);
  51. this.raf = null;
  52. }
  53. }
  54. }