import { EnvironmentComponent, MouseComponent, ViewportComponent, EventEmitter, LevelComponent, Engine, assetManager, PhysicsWorldComponent, } from '@freeblox/engine'; import { GameEvents } from '../types/events'; import { GameplayComponent } from './gameplay'; const INVERSE_MAX_FPS = 1000 / 60; const INVERSE_MAX_FPS_S = 1 / 60; export class Game extends Engine { public events = new EventEmitter(); private delta = 0; mount(element: HTMLElement): void { super.mount(element); this.use(ViewportComponent); this.use(EnvironmentComponent); this.use(LevelComponent); this.use(MouseComponent); this.use(PhysicsWorldComponent); this.use(GameplayComponent); this.getComponent(ViewportComponent).setSizeFromViewport(); this.start(); } loop(now: number): void { this.getDelta(now); this.running && requestAnimationFrame((ts) => this.loop(ts)); this.render.render(); while (this.delta >= INVERSE_MAX_FPS) { this.update(INVERSE_MAX_FPS_S); this.delta -= INVERSE_MAX_FPS; } } getDelta(now: number): number { this.delta += now - this.lastTick; this.lastTick = now; return this.delta; } async loadLevel(path: string) { const data = await assetManager.loadJsonData(path); await this.getComponent(LevelComponent).deserializeLevelSave(data); this.events.emit('initialized'); } }