From 22b06efe2c2646a01535b5bbf5f3cc57de81ad0d Mon Sep 17 00:00:00 2001 From: Matthias Schiffer Date: Thu, 1 Nov 2018 00:44:49 +0100 Subject: controller: more GameContext cleanup, introduce ticks --- src/controller/gamecontext.ts | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) (limited to 'src/controller') diff --git a/src/controller/gamecontext.ts b/src/controller/gamecontext.ts index 4d86abf..792e160 100644 --- a/src/controller/gamecontext.ts +++ b/src/controller/gamecontext.ts @@ -12,18 +12,13 @@ import { vec2 } from 'gl-matrix'; export class GameContext { public static async load(renderer: Renderer): Promise { - const [ - mapView, - entity, - ] = await Promise.all([ - GameContext.loadMap(renderer), - loadSimpleEntity(renderer, 'simple_square'), - ]); + const mapView = this.loadMap(renderer); + const entity = loadSimpleEntity(renderer, 'simple_square'); return new GameContext( renderer, - mapView, - entity, + await mapView, + await entity, ); } @@ -34,7 +29,9 @@ export class GameContext { private time: number|null = null; - private readonly speed = 1 / 100; + private readonly tick = 10; // ms per tick + private readonly speed = 0.05; // movement per tick + private readonly maxSkip = 20; // maximum ticks to process in a single render step private readonly input: DirectionHandler; @@ -64,17 +61,24 @@ export class GameContext { return diff; } + private updateStep(): void { + vec2.scaleAndAdd(this.entityPos, this.entityPos, this.entityMovement, this.speed); + } + private update(time: number): void { - const diff = this.updateTime(time); + const diff = Math.min(this.maxSkip, this.updateTime(time)); - if (vec2.sqrLen(this.entityMovement) > 0) - vec2.scaleAndAdd(this.entityPos, this.entityPos, this.entityMovement, diff * this.speed); - else + if (vec2.sqrLen(this.entityMovement) === 0) { this.renderer.snapToGrid(this.entityPos, this.entityPos); + return; + } + + for (let i = 0; i < diff; i++) + this.updateStep(); } private render = (time: number) => { - this.update(time); + this.update(Math.round(time / this.tick)); this.renderer.setCenter(this.entityPos); this.renderer.clear(); -- cgit v1.2.3