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

52 lines
1.1 KiB
JavaScript
Raw Normal View History

2024-06-11 01:41:19 -05:00
import {System} from '@/ecs/index.js';
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) {
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;
}
if (Math.abs(Camera.x - px) < 0.1) {
Camera.x = px;
}
if (Math.abs(Camera.y - py) < 0.1) {
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.1, Math.abs(dx))),
Camera.y + (Math.sign(dy) * Math.max(0.1, Math.abs(dy))),
];
2024-06-11 01:41:19 -05:00
}
}
}