123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- import Player from './entities/Player.js';
- import structures from './structures.js';
-
- export default class Level {
- constructor(canvas) {
- this.step = 1 / 120;
- this.stepLimit = 2;
-
- this.canvas = canvas;
- this.ctx = canvas.getContext("2d");
- this.lastTime = null;
- this.raf = null;
- this.timeAcc = 0;
- this.entities = [];
-
- this.evts = [];
-
- this.structure = structures.floor(2, 2, 1);
- }
-
- 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.ctx.resetTransform();
- this.ctx.beginPath();
- this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
-
- this.entities.forEach(ent => ent.draw(this.ctx));
- this.structure.draw(this.ctx);
- }
-
- update(time) {
- if (this.lastTime != null) {
- let dt = (time - this.lastTime) / 1000;
-
- this.timeAcc += dt;
- if (this.timeAcc > this.stepLimit) {
- console.warn(
- "Attempt to simulate "+this.timeAcc.toFixed(2)+" "+
- "seconds, which is over the limit ("+this.stepLimit+"s). "+
- "Resetting accumulator.");
- this.timeAcc = dt;
- }
-
- let nticks = 0;
- while (this.timeAcc >= this.step) {
- nticks += 1;
- this.physics(this.step);
- this.timeAcc -= this.step;
- }
-
- this.draw();
- }
-
- this.lastTime = time;
- this.raf = requestAnimationFrame(this.update.bind(this));
- }
-
- start() {
- if (this.raf == null) {
- this.lastTime = null;
- this.update();
- console.log("Started.");
- }
- }
-
- stop() {
- if (this.raf != null) {
- cancelAnimationFrame(this.raf);
- this.raf = null;
- console.log("Stopped.");
- }
- }
- }
|