silphius/app/ecs/systems/follow-camera.js
2024-07-20 05:07:39 -05:00

60 lines
1.5 KiB
JavaScript

import {System} from '@/ecs/index.js';
// import {RESOLUTION} from '@/util/constants.js'
// const [hx, hy] = [RESOLUTION.x / 2, RESOLUTION.y / 2];
export default class FollowCamera extends System {
static queries() {
return {
default: ['Camera', 'Position'],
};
}
reindex(entities) {
super.reindex(entities);
for (const id of entities) {
this.updateCamera(1, this.ecs.get(id));
}
}
tick(elapsed) {
for (const {id} of this.select('default')) {
this.updateCamera(elapsed * 3, this.ecs.get(id));
}
}
updateCamera(portion, entity) {
const {Camera, Position} = entity;
if (Camera && Position) {
// const {AreaSize: {x, y}} = this.ecs.get(1);
// const [px, py] = [
// Math.max(hx, Math.min(Math.round(Position.x), x - hx)),
// Math.max(hy, Math.min(Math.round(Position.y), y - hy)),
// ];
const [px, py] = [
Math.round(Position.x),
Math.round(Position.y),
];
if (Camera.x === px && Camera.y === py) {
return;
}
if (Math.abs(Camera.x - px) < 0.01) {
Camera.x = px;
}
if (Math.abs(Camera.y - py) < 0.01) {
Camera.y = py;
}
const [dx, dy] = [
(px - Camera.x) * portion,
(py - Camera.y) * portion,
];
[Camera.x, Camera.y] = [
Camera.x + (Math.sign(dx) * Math.max(0.01, Math.abs(dx))),
Camera.y + (Math.sign(dy) * Math.max(0.01, Math.abs(dy))),
];
}
}
}