import Player from './entities/Player'; export default class Level { constructor(canvas) { this.step = 1 / 120; this.canvas = canvas; this.ctx = canvas.getContext("2d"); this.lastTime = null; this.raf = null; this.timeAcc = 0; this.entities = []; } spawn(ent, x, y) { ent.bounds.pos.set(x, y); this.entities.push(ent); ent.init(); } physics(dt) { this.entities.forEach(ent => ent.update(dt)); this.entities.forEach(ent => { ent.bounds.pos.x += ent.velocity.x * dt; ent.bounds.pos.y += ent.velocity.y * dt; }); } draw() { this.canvas.width = window.innerWidth; this.canvas.height = window.innerHeight; this.entities.forEach(ent => ent.draw(this.ctx)); } update(time) { if (this.lastTime != null) { let dt = (time - this.lastTime) / 1000; this.timeAcc += dt; while (this.timeAcc > this.step) { this.physics(this.step); this.timeAcc -= this.step; } this.draw(); } this.lastTime = time; this.raf = requestAnimationFrame(time => this.update(time)); } start() { this.stop(); this.lastTime = null; this.update(); } stop() { if (this.raf != null) { cancelAnimationFrame(this.raf); this.raf = null; } } }