controller: more GameContext cleanup, introduce ticks
This commit is contained in:
parent
1ae0884a73
commit
22b06efe2c
1 changed files with 20 additions and 16 deletions
|
@ -12,18 +12,13 @@ import { vec2 } from 'gl-matrix';
|
|||
|
||||
export class GameContext {
|
||||
public static async load(renderer: Renderer): Promise<GameContext> {
|
||||
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 update(time: number): void {
|
||||
const diff = this.updateTime(time);
|
||||
private updateStep(): void {
|
||||
vec2.scaleAndAdd(this.entityPos, this.entityPos, this.entityMovement, this.speed);
|
||||
}
|
||||
|
||||
if (vec2.sqrLen(this.entityMovement) > 0)
|
||||
vec2.scaleAndAdd(this.entityPos, this.entityPos, this.entityMovement, diff * this.speed);
|
||||
else
|
||||
private update(time: number): void {
|
||||
const diff = Math.min(this.maxSkip, this.updateTime(time));
|
||||
|
||||
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();
|
||||
|
|
Reference in a new issue