Files
dflike/server/src/systems/movementSystem.ts
T
2026-03-08 22:50:48 +00:00

47 lines
1.6 KiB
TypeScript

import { Direction, MOVE_SPEED, type Movement, type Position, type SocialState } from '@dflike/shared';
import type { World } from '../ecs/World.js';
import type { GatheringState } from './gatheringSystem.js';
function directionFromDelta(dx: number, dy: number): number {
if (Math.abs(dx) > Math.abs(dy)) return dx > 0 ? Direction.RIGHT : Direction.LEFT;
return dy > 0 ? Direction.DOWN : Direction.UP;
}
export function movementSystem(world: World): void {
for (const entity of world.query('position', 'movement')) {
const movement = world.getComponent<Movement>(entity, 'movement')!;
const pos = world.getComponent<Position>(entity, 'position')!;
const socialState = world.getComponent<SocialState>(entity, 'socialState');
if (socialState && socialState.phase !== 'none') continue;
const gatheringState = world.getComponent<GatheringState>(entity, 'gatheringState');
if (gatheringState) continue;
if (movement.state !== 'walking' || movement.path.length === 0) {
if (movement.state === 'walking' && movement.path.length === 0) {
movement.state = 'idle';
movement.target = null;
movement.moveProgress = 0;
}
continue;
}
movement.moveProgress += MOVE_SPEED;
if (movement.moveProgress >= 1) {
movement.moveProgress -= 1;
const next = movement.path.shift()!;
movement.direction = directionFromDelta(next.x - pos.x, next.y - pos.y);
pos.x = next.x;
pos.y = next.y;
if (movement.path.length === 0) {
movement.state = 'idle';
movement.target = null;
movement.moveProgress = 0;
}
}
}
}