slime/src/systems/PlayerControllerSystem.js

71 lines
2.1 KiB
JavaScript

import { System } from '../core/System.js';
import { SystemName, ComponentType } from '../core/Constants.js';
export class PlayerControllerSystem extends System {
constructor() {
super(SystemName.PLAYER_CONTROLLER);
this.requiredComponents = [ComponentType.POSITION, ComponentType.VELOCITY];
this.priority = 5;
this.playerEntity = null;
}
process(deltaTime, entities) {
// Find player entity (entity with Evolution component)
if (!this.playerEntity) {
this.playerEntity = entities.find(e => e.hasComponent(ComponentType.EVOLUTION));
}
if (!this.playerEntity) return;
const inputSystem = this.engine.systems.find(s => s.name === SystemName.INPUT);
if (!inputSystem) return;
const velocity = this.playerEntity.getComponent(ComponentType.VELOCITY);
const position = this.playerEntity.getComponent(ComponentType.POSITION);
if (!velocity || !position) return;
// Movement input
let moveX = 0;
let moveY = 0;
const moveSpeed = 100; // Scaled down for 320x240
if (inputSystem.isKeyPressed('w') || inputSystem.isKeyPressed('arrowup')) {
moveY -= 1;
}
if (inputSystem.isKeyPressed('s') || inputSystem.isKeyPressed('arrowdown')) {
moveY += 1;
}
if (inputSystem.isKeyPressed('a') || inputSystem.isKeyPressed('arrowleft')) {
moveX -= 1;
}
if (inputSystem.isKeyPressed('d') || inputSystem.isKeyPressed('arrowright')) {
moveX += 1;
}
// Normalize diagonal movement
if (moveX !== 0 && moveY !== 0) {
moveX *= 0.707;
moveY *= 0.707;
}
// Apply movement
velocity.vx = moveX * moveSpeed;
velocity.vy = moveY * moveSpeed;
// Face mouse or movement direction
const mouse = inputSystem.getMousePosition();
const dx = mouse.x - position.x;
const dy = mouse.y - position.y;
if (Math.abs(dx) > 0.1 || Math.abs(dy) > 0.1) {
position.rotation = Math.atan2(dy, dx);
} else if (moveX !== 0 || moveY !== 0) {
position.rotation = Math.atan2(moveY, moveX);
}
}
getPlayerEntity() {
return this.playerEntity;
}
}