Files
CINC/systems/SelectionSystem.js
T
2025-12-31 00:30:38 +08:00

91 lines
2.3 KiB
JavaScript

// systems/SelectionSystem.js
import { clearSelection, addToSelection, setActiveUnit } from './ControlMode.js';
export class SelectionSystem {
constructor(scene) {
this.scene = scene;
this.selectionBox = null;
scene.events.on('selection-start', this.onStart, this);
scene.events.on('selection-update', this.onUpdate, this);
scene.events.on('selection-end', this.onEnd, this);
scene.events.on('select-unit', this.onSelectUnit, this);
}
onStart(pos) {
if (!this.selectionBox) {
this.selectionBox = this.scene.add.rectangle(pos.x, pos.y, 1, 1, 0x00ff00, 0.3)
.setStrokeStyle(1, 0xffffff)
.setVisible(true);
} else {
this.selectionBox.setPosition(pos.x, pos.y).setSize(1, 1).setVisible(true);
}
}
onUpdate(rect) {
if (this.selectionBox && this.selectionBox.visible) {
// 更新选择框的位置和大小
this.selectionBox.setPosition(rect.centerX, rect.centerY);
this.selectionBox.setSize(rect.width, rect.height);
}
}
onSelectUnit(unit) {
// 清除所有单位的选中状态
this.scene.unitGroup.getChildren().forEach(u => {
if (u.setSelected) {
u.setSelected(false);
}
});
// 清除当前选择
clearSelection();
// 选择点击的单位
setActiveUnit(unit);
addToSelection(unit);
// 设置选中状态
if (unit.setSelected) {
unit.setSelected(true);
}
this.scene.events.emit('units-selected', [unit]);
}
onEnd(rect) {
if (this.selectionBox) {
this.selectionBox.setVisible(false);
}
const units = this.scene.unitGroup.getChildren();
const selected = units.filter(unit => {
const unitRect = unit.getBounds();
return Phaser.Geom.Rectangle.Overlaps(rect, unitRect);
});
// 先清除所有单位的选中状态
units.forEach(unit => {
if (unit.setSelected) {
unit.setSelected(false);
}
});
clearSelection();
if (selected.length > 0) {
// 先设置激活单位
setActiveUnit(selected[0]);
// 然后添加所有选中的单位(包括激活单位)
selected.forEach(unit => {
addToSelection(unit);
if (unit.setSelected) {
unit.setSelected(true);
}
});
this.scene.events.emit('units-selected', selected);
}
}
}