Skip to content

Commit

Permalink
Fix game logic framerate being tied to screen refresh rate
Browse files Browse the repository at this point in the history
  • Loading branch information
halbu committed Nov 17, 2018
1 parent e019e67 commit 5deaa61
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 9 deletions.
11 changes: 7 additions & 4 deletions built/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ Constants.WINCH_Y_OFFSET = 12;
Constants.PERSON_HEIGHT = 18;
Constants.PERSON_LEFTMOST_WALK_POINT = 440;
Constants.PERSON_RIGHTMOST_WALK_POINT = 750;
Constants.MILLISECONDS_PER_FRAME = 17; // close enough
Constants.COLORS = {
DRAW_COLOR: '#ffffff',
SCANLINE_COLOR: '#006000',
Expand Down Expand Up @@ -249,7 +250,12 @@ class HELI {
this.inputManager.clearInput();
this.overdrawScanlines();
this.applyGlfx();
this.awaitNextFrame();
this.deltaTime = performance.now() - this.lastFrameTime;
while (this.deltaTime < Constants.MILLISECONDS_PER_FRAME) {
this.deltaTime = performance.now() - this.lastFrameTime;
}
this.lastFrameTime = performance.now();
window.requestAnimationFrame(() => { this.coreGameLoop(); });
}
applyGlfx() {
// Load the latest glfxSourceCanvas frame
Expand Down Expand Up @@ -285,9 +291,6 @@ class HELI {
coinflip() {
return this.oneIn(2);
}
awaitNextFrame() {
window.requestAnimationFrame(() => { this.coreGameLoop(); });
}
}
class InputManager {
constructor(cnv) {
Expand Down
2 changes: 2 additions & 0 deletions src/core/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ class Constants {
public static readonly PERSON_LEFTMOST_WALK_POINT = 440;
public static readonly PERSON_RIGHTMOST_WALK_POINT = 750;

public static readonly MILLISECONDS_PER_FRAME = 17; // close enough

public static readonly COLORS = {
DRAW_COLOR: '#ffffff',
SCANLINE_COLOR: '#006000',
Expand Down
14 changes: 9 additions & 5 deletions src/core/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ class HELI {
public ctx: CanvasRenderingContext2D;

public lastFrameTime: number;
public deltaTime: number;

public inputManager: InputManager;
public scanlineOffset = 0;
public activeScreen: IAppScreen;
Expand Down Expand Up @@ -73,7 +75,13 @@ class HELI {
this.overdrawScanlines();
this.applyGlfx();

this.awaitNextFrame();
this.deltaTime = performance.now() - this.lastFrameTime;
while (this.deltaTime < Constants.MILLISECONDS_PER_FRAME) {
this.deltaTime = performance.now() - this.lastFrameTime;
}

this.lastFrameTime = performance.now();
window.requestAnimationFrame(() => {this.coreGameLoop(); });
}

public applyGlfx(): void {
Expand Down Expand Up @@ -113,8 +121,4 @@ class HELI {
public coinflip(): boolean {
return this.oneIn(2);
}

public awaitNextFrame(): void {
window.requestAnimationFrame(() => { this.coreGameLoop(); });
}
}

0 comments on commit 5deaa61

Please sign in to comment.