1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- 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;
- }
- }
- }
|