Skip to content

Commit

Permalink
Camera: Center camera properly on resize
Browse files Browse the repository at this point in the history
  • Loading branch information
RyanGrieb committed Nov 25, 2023
1 parent 6ef16d9 commit aa6e420
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
12 changes: 12 additions & 0 deletions client/src/Game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ export class Game {
private static wrappedTextCache: { [key: string]: [string, number, number] } =
{};
private static resizeTimer: NodeJS.Timeout;
private static oldWidth: number;
private static oldHeight: number;

private constructor() {}

Expand Down Expand Up @@ -176,6 +178,8 @@ export class Game {
clearTimeout(this.resizeTimer);

this.resizeTimer = setTimeout(() => {
this.oldWidth = this.canvas.width;
this.oldHeight = this.canvas.height;
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
if (this.currentScene) {
Expand Down Expand Up @@ -594,6 +598,14 @@ export class Game {
return this.canvas.width;
}

public static getOldHeight(): number {
return this.oldHeight;
}

public static getOldWidth(): number {
return this.oldWidth;
}

public static getCanvasContext() {
return this.canvasContext;
}
Expand Down
8 changes: 8 additions & 0 deletions client/src/scene/Scene.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,14 @@ export abstract class Scene {

public restoreCamera() {
this.camera = Camera.fromCamera(this.oldCamera);
// Shift the camera position to account for our new window size (We do this for alignment)
const wDiff = Game.getWidth() - Game.getOldWidth();
const hDiff = Game.getHeight() - Game.getOldHeight();

this.camera.setPosition(
this.camera.getX() + wDiff / 2,
this.camera.getY() + hDiff / 2
);
}

public sortSceneObjects() {
Expand Down

0 comments on commit aa6e420

Please sign in to comment.