Files
CINC/systems/SelectionSystem.js
T
2025-12-31 18:26:48 +08:00

131 lines
4.4 KiB
JavaScript

// 选择系统:处理游戏中单位的选择逻辑,包括单个单位点击选择和多个单位框选
// 从ControlMode.js导入选择管理相关的函数
import { clearSelection, addToSelection, setActiveUnit } from './ControlMode.js';
// 导出SelectionSystem类,用于创建选择系统实例
export class SelectionSystem {
// 构造函数:初始化选择系统
// @param {Object} scene - 游戏场景实例
constructor(scene) {
// 保存场景引用,用于访问游戏世界和发送事件
this.scene = scene;
// 选择框对象,用于显示框选区域
// 初始值为null,表示当前没有选择框
this.selectionBox = null;
// 注册事件监听器,处理选择相关的事件
// 当开始选择时调用onStart方法
scene.events.on('selection-start', this.onStart, this);
// 当选择区域更新时调用onUpdate方法
scene.events.on('selection-update', this.onUpdate, this);
// 当选择结束时调用onEnd方法
scene.events.on('selection-end', this.onEnd, this);
// 当选择单个单位时调用onSelectUnit方法
scene.events.on('select-unit', this.onSelectUnit, this);
}
// 处理选择开始事件
// @param {Object} pos - 选择开始的位置,包含x和y坐标
onStart(pos) {
// 如果选择框不存在,则创建一个新的选择框
if (!this.selectionBox) {
// 在游戏世界中创建一个矩形作为选择框
this.selectionBox = this.scene.add.rectangle(pos.x, pos.y, 1, 1, 0x00ff00, 0.3)
.setStrokeStyle(1, 0xffffff) // 设置白色边框,宽度为1像素
.setVisible(true); // 设置选择框可见
} else {
// 如果选择框已存在,重置其位置和大小并设置可见
this.selectionBox.setPosition(pos.x, pos.y).setSize(1, 1).setVisible(true);
}
}
// 处理选择区域更新事件
// @param {Object} rect - 更新后的选择区域矩形
onUpdate(rect) {
// 如果选择框存在且可见
if (this.selectionBox && this.selectionBox.visible) {
// 更新选择框的位置到矩形中心
this.selectionBox.setPosition(rect.centerX, rect.centerY);
// 更新选择框的大小到矩形的宽度和高度
this.selectionBox.setSize(rect.width, rect.height);
}
}
// 处理选择单个单位事件
// @param {Object} unit - 被选择的单位对象
onSelectUnit(unit) {
// 清除所有单位的选中状态
this.scene.unitGroup.getChildren().forEach(u => {
// 检查单位是否有setSelected方法
if (u.setSelected) {
// 设置单位为未选中状态
u.setSelected(false);
}
});
// 清除当前的选择列表和激活单位
clearSelection();
// 设置点击的单位为激活单位
setActiveUnit(unit);
// 将点击的单位添加到选择列表
addToSelection(unit);
// 设置点击的单位为选中状态
if (unit.setSelected) {
unit.setSelected(true);
}
// 发送单位选中事件,通知其他系统
this.scene.events.emit('units-selected', [unit]);
}
// 处理选择结束事件
// @param {Object} rect - 最终的选择区域矩形
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);
}
}
}