mirror of
http://junepve.top:3000/chicrobot/CINC.git
synced 2026-10-29 19:41:29 +08:00
86 lines
2.7 KiB
JavaScript
86 lines
2.7 KiB
JavaScript
// systems/InputSystem.js
|
|
import { clearSelection, setActiveUnit } from './ControlMode.js';
|
|
|
|
export class InputSystem {
|
|
constructor(scene) {
|
|
this.scene = scene;
|
|
this.selectionStart = null;
|
|
|
|
// 初始化键盘
|
|
const kb = scene.input.keyboard;
|
|
this.keys = {
|
|
up: [kb.addKey(Phaser.Input.Keyboard.KeyCodes.W), kb.addKey(Phaser.Input.Keyboard.KeyCodes.UP)],
|
|
down: [kb.addKey(Phaser.Input.Keyboard.KeyCodes.S), kb.addKey(Phaser.Input.Keyboard.KeyCodes.DOWN)],
|
|
left: [kb.addKey(Phaser.Input.Keyboard.KeyCodes.A), kb.addKey(Phaser.Input.Keyboard.KeyCodes.LEFT)],
|
|
right: [kb.addKey(Phaser.Input.Keyboard.KeyCodes.D), kb.addKey(Phaser.Input.Keyboard.KeyCodes.RIGHT)]
|
|
};
|
|
|
|
// 鼠标/触摸事件
|
|
scene.input.on('pointerdown', this.onPointerDown, this);
|
|
scene.input.on('pointerup', this.onPointerUp, this);
|
|
}
|
|
|
|
isKeyDown(keyGroup) {
|
|
return keyGroup.some(key => key.isDown);
|
|
}
|
|
|
|
update() {
|
|
// 键盘相对移动(仅当有激活单位)
|
|
const dir = { x: 0, y: 0 };
|
|
if (this.isKeyDown(this.keys.left)) dir.x -= 1;
|
|
if (this.isKeyDown(this.keys.right)) dir.x += 1;
|
|
if (this.isKeyDown(this.keys.up)) dir.y -= 1;
|
|
if (this.isKeyDown(this.keys.down)) dir.y += 1;
|
|
|
|
if (dir.x !== 0 || dir.y !== 0) {
|
|
this.scene.events.emit('move-relative', dir);
|
|
}
|
|
}
|
|
|
|
onPointerDown(pointer) {
|
|
if (pointer.leftButtonDown()) {
|
|
const worldX = pointer.worldX;
|
|
const worldY = pointer.worldY;
|
|
|
|
// 检查是否点中某个单位
|
|
let clickedUnit = null;
|
|
this.scene.unitGroup.getChildren().forEach(unit => {
|
|
const bounds = unit.getBounds();
|
|
if (worldX >= bounds.x && worldX <= bounds.right &&
|
|
worldY >= bounds.y && worldY <= bounds.bottom) {
|
|
clickedUnit = unit;
|
|
}
|
|
});
|
|
|
|
if (clickedUnit) {
|
|
// 切换控制目标
|
|
this.scene.events.emit('select-unit', clickedUnit);
|
|
} else {
|
|
// 开始框选或移动指令
|
|
this.selectionStart = { x: pointer.x, y: pointer.y };
|
|
this.scene.events.emit('selection-start', this.selectionStart);
|
|
}
|
|
}
|
|
}
|
|
|
|
onPointerUp(pointer) {
|
|
if (this.selectionStart) {
|
|
const rect = new Phaser.Geom.Rectangle(
|
|
Math.min(this.selectionStart.x, pointer.x),
|
|
Math.min(this.selectionStart.y, pointer.y),
|
|
Math.abs(pointer.x - this.selectionStart.x),
|
|
Math.abs(pointer.y - this.selectionStart.y)
|
|
);
|
|
|
|
// 如果框太小,视为“点击地面移动”
|
|
if (rect.width < 10 && rect.height < 10) {
|
|
this.scene.events.emit('move-to-point', pointer.worldX, pointer.worldY);
|
|
} else {
|
|
// 否则执行框选
|
|
this.scene.events.emit('selection-end', rect);
|
|
}
|
|
|
|
this.selectionStart = null;
|
|
}
|
|
}
|
|
} |