silphius/app/ecs/systems/follow-camera.js

60 lines
1.5 KiB
JavaScript
Raw Normal View History

2024-06-11 01:41:19 -05:00
import {System} from '@/ecs/index.js';
2024-07-20 04:41:00 -05:00
// import {RESOLUTION} from '@/util/constants.js'
2024-06-11 01:41:19 -05:00
// const [hx, hy] = [RESOLUTION.x / 2, RESOLUTION.y / 2];
2024-06-11 01:41:19 -05:00
export default class FollowCamera extends System {
2024-06-23 02:45:05 -05:00
static queries() {
return {
default: ['Camera', 'Position'],
};
}
2024-06-11 01:41:19 -05:00
reindex(entities) {
super.reindex(entities);
for (const id of entities) {
2024-06-23 02:45:05 -05:00
this.updateCamera(1, this.ecs.get(id));
2024-06-11 01:41:19 -05:00
}
}
2024-06-23 02:45:05 -05:00
tick(elapsed) {
2024-06-26 07:41:07 -05:00
for (const {id} of this.select('default')) {
this.updateCamera(elapsed * 3, this.ecs.get(id));
2024-06-11 01:41:19 -05:00
}
}
2024-06-23 02:45:05 -05:00
updateCamera(portion, entity) {
2024-06-11 01:41:19 -05:00
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)),
// ];
2024-06-23 02:45:05 -05:00
const [px, py] = [
2024-06-25 08:41:20 -05:00
Math.round(Position.x),
Math.round(Position.y),
2024-06-23 02:45:05 -05:00
];
if (Camera.x === px && Camera.y === py) {
return;
}
2024-07-01 13:44:16 -05:00
if (Math.abs(Camera.x - px) < 0.01) {
2024-06-23 02:45:05 -05:00
Camera.x = px;
}
2024-07-01 13:44:16 -05:00
if (Math.abs(Camera.y - py) < 0.01) {
2024-06-23 02:45:05 -05:00
Camera.y = py;
}
const [dx, dy] = [
(px - Camera.x) * portion,
(py - Camera.y) * portion,
];
[Camera.x, Camera.y] = [
2024-07-01 13:44:16 -05:00
Camera.x + (Math.sign(dx) * Math.max(0.01, Math.abs(dx))),
Camera.y + (Math.sign(dy) * Math.max(0.01, Math.abs(dy))),
2024-06-23 02:45:05 -05:00
];
2024-06-11 01:41:19 -05:00
}
}
}