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,
|
2024-09-20 00:46:42 -05:00
|
|
|
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;
|
2024-09-20 00:46:42 -05:00
|
|
|
this.target = target;
|
|
|
|
this.eventEmitter.on("levelChanged", () => {
|
2024-09-14 23:51:24 -05:00
|
|
|
this.x = x;
|
|
|
|
this.y = y;
|
|
|
|
});
|
2024-09-20 00:46:42 -05:00
|
|
|
this.eventEmitter.on("targetChanged", (target) => {
|
|
|
|
this.target = target;
|
2024-09-13 23:30:28 -05:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2024-09-20 00:46:42 -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)
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2024-09-20 00:46:42 -05:00
|
|
|
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;
|
2024-09-20 00:46:42 -05:00
|
|
|
this.x = Math.max(
|
|
|
|
0,
|
|
|
|
Math.min(centerX - this.width / 2, width * TILE_SIZE - this.width)
|
2024-09-13 23:30:28 -05:00
|
|
|
);
|
2024-09-20 00:46:42 -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
|
|
|
}
|
|
|
|
}
|