import {RESOLUTION} from '@/constants.js' import {System} from '@/ecs/index.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 [, , entityId] of this.select('default')) { this.updateCamera(elapsed * 3, this.ecs.get(entityId)); } } updateCamera(portion, entity) { const {Camera, Position} = entity; if (Camera && Position) { 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.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))), ]; } } }