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

61 lines
1.6 KiB
JavaScript
Raw Normal View History

2024-09-13 23:30:28 -05:00
import { 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 18:38:50 -05:00
constructor({ gameObjects = [], x = 0, y = 0, width = 160, height = 120 }) {
2024-09-13 21:45:59 -05:00
super({ x, y });
2024-09-14 18:38:50 -05:00
this.gameObjects = gameObjects;
2024-09-13 21:45:59 -05:00
this.x = x;
this.y = y;
this.width = width;
this.height = height;
2024-09-13 23:30:28 -05:00
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) {
2024-09-14 18:38:50 -05:00
const [item] = this.gameObjects;
const { height, width } = item.selected ?? item;
2024-09-13 23:30:28 -05:00
this.x = Math.min(
2024-09-14 18:38:50 -05:00
Math.max(this.x + dx * Math.floor(delta * 100), 0),
2024-09-13 23:30:28 -05:00
width * TILE_SIZE - this.width
);
this.y = Math.min(
2024-09-14 18:38:50 -05:00
Math.max(this.y + dy * Math.floor(delta * 100), 0),
2024-09-13 23:30:28 -05:00
height * TILE_SIZE - this.height
);
2024-09-13 21:45:59 -05:00
}
}