67 lines
1.8 KiB
JavaScript
67 lines
1.8 KiB
JavaScript
import { TILE_SIZE } from "../constants.js";
|
|
import { GameObject } from "./game-object.js";
|
|
import { MapManagement } from "./map-management.js";
|
|
|
|
export class Camera extends GameObject {
|
|
constructor({ mapManagement, x = 0, y = 0, width = 160, height = 120 }) {
|
|
super({ x, y });
|
|
this.mapManagement = mapManagement;
|
|
this.gameObjects = [mapManagement];
|
|
this.x = x;
|
|
this.y = y;
|
|
this.width = width;
|
|
this.height = height;
|
|
this.keys = [
|
|
{ key: "ArrowUp", pressed: false, value: [0, -1] },
|
|
{ key: "ArrowDown", pressed: false, value: [0, 1] },
|
|
{ key: "ArrowLeft", pressed: false, value: [-1, 0] },
|
|
{ key: "ArrowRight", pressed: false, value: [1, 0] },
|
|
];
|
|
this.availableKeys = this.keys.reduce(
|
|
(acc, item) => ({ ...acc, [item.key]: item }),
|
|
{}
|
|
);
|
|
}
|
|
|
|
update(delta) {
|
|
this.keys.forEach((item) => {
|
|
if (item.pressed) {
|
|
this.moveCamera(...item.value, delta);
|
|
}
|
|
});
|
|
}
|
|
|
|
onKeyPressed(key) {
|
|
if (!this.availableKeys[key]) return;
|
|
this.availableKeys[key].pressed = true;
|
|
}
|
|
|
|
onKeyReleased(key) {
|
|
if (!this.availableKeys[key]) return;
|
|
this.availableKeys[key].pressed = false;
|
|
}
|
|
|
|
render(ctx) {
|
|
this.gameObjects.forEach((item) =>
|
|
item.render(ctx, this.x, this.y, this.width, this.height)
|
|
);
|
|
}
|
|
|
|
moveCamera(dx, dy, delta) {
|
|
const { levelConfig } = this.mapManagement.selected;
|
|
const layer = levelConfig.layers[0];
|
|
const { height, width } = layer;
|
|
|
|
const floorX = dx > 0 ? Math.floor : Math.ceil;
|
|
const floorY = dy > 0 ? Math.floor : Math.ceil;
|
|
|
|
this.x = Math.min(
|
|
Math.max(this.x + floorX(dx * (delta * 100)), 0),
|
|
width * TILE_SIZE - this.width
|
|
);
|
|
this.y = Math.min(
|
|
Math.max(this.y + floorY(dy * (delta * 100)), 0),
|
|
height * TILE_SIZE - this.height
|
|
);
|
|
}
|
|
}
|