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

53 lines
1.3 KiB
JavaScript
Raw Normal View History

2024-09-14 23:57:43 -05:00
import { GAME_HEIGHT, GAME_WIDTH, TILE_SIZE } from "../constants.js";
2024-09-13 21:45:59 -05:00
import { GameObject } from "./game-object.js";
export class Camera extends GameObject {
2024-09-14 21:19:46 -05:00
constructor({
gameObjects = [],
x = 0,
y = 0,
2024-09-14 23:57:43 -05:00
width = GAME_WIDTH,
height = GAME_HEIGHT,
2024-09-14 21:19:46 -05:00
speed = 1,
target = { x: 0, y: 0, width: 0, height: 0 }, // A camera that follows a target
2024-09-14 21:19:46 -05:00
}) {
2024-09-17 23:16:36 -05:00
super({ x, y, gameObjects, width, height });
2024-09-14 21:19:46 -05:00
this.speed = speed;
this.target = target;
this.eventEmitter.on("levelChanged", () => {
this.x = x;
this.y = y;
});
this.eventEmitter.on("targetChanged", (target) => {
this.target = target;
2024-09-13 23:30:28 -05:00
});
}
update(delta) {
super.update(delta);
this.followTarget();
2024-09-13 23:30:28 -05:00
}
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;
2024-09-14 18:38:50 -05:00
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)
2024-09-13 23:30:28 -05:00
);
this.y = Math.max(
0,
Math.min(centerY - this.height / 2, height * TILE_SIZE - this.height)
2024-09-13 23:30:28 -05:00
);
2024-09-13 21:45:59 -05:00
}
}