game-engine/modules/game-objects/camera.js

52 lines
1.3 KiB
JavaScript

import { GAME_HEIGHT, GAME_WIDTH, TILE_SIZE } from "../constants.js";
import { GameObject } from "./game-object.js";
export class Camera extends GameObject {
constructor({
gameObjects = [],
x = 0,
y = 0,
width = GAME_WIDTH,
height = GAME_HEIGHT,
speed = 1,
target = { x: 0, y: 0, width: 0, height: 0 }, // A camera that follows a target
}) {
super({ x, y, gameObjects, width, height });
this.speed = speed;
this.target = target;
this.eventEmitter.on("levelChanged", () => {
this.x = x;
this.y = y;
});
this.eventEmitter.on("targetChanged", (target) => {
this.target = target;
});
}
update(delta) {
super.update(delta);
this.followTarget();
}
render(ctx) {
this.gameObjects.forEach((item) =>
item.render(ctx, this.x, this.y, this.width, this.height)
);
}
followTarget() {
const { x, y, width: tWidth, height: tHeight } = this.target;
const centerX = x + tWidth / 2;
const centerY = y + tHeight / 2;
const [item] = this.gameObjects;
const { height, width } = item.selected ?? item;
this.x = Math.max(
0,
Math.min(centerX - this.width / 2, width * TILE_SIZE - this.width)
);
this.y = Math.max(
0,
Math.min(centerY - this.height / 2, height * TILE_SIZE - this.height)
);
}
}