Files
CINC/systems/CommandSystem.js
T

60 lines
2.6 KiB
JavaScript

// 命令系统:处理玩家对游戏单位的各种命令(如移动、选择等)
// 从ControlMode.js导入当前激活的单位和选中的单位列表
import { activeUnit, selectedUnits } from './ControlMode.js';
// 导出CommandSystem类,用于创建命令系统实例
export class CommandSystem {
// 构造函数:初始化命令系统
constructor(scene) {
// 保存场景引用,用于访问游戏世界和发送事件
this.scene = scene;
// 监听场景中的移动相关事件
// 当'move-relative'事件触发时,调用onMoveRelative方法
scene.events.on('move-relative', this.onMoveRelative, this);
// 当'move-to-point'事件触发时,调用onMoveToPoint方法
scene.events.on('move-to-point', this.onMoveToPoint, this);
// 当'select-unit'事件触发时,调用onSelectUnit方法
scene.events.on('select-unit', this.onSelectUnit, this);
}
// 处理相对移动命令:根据方向向量移动单位
onMoveRelative(dir) {
// 确定移动目标单位:优先使用选中的单位列表,如果没有选中单位则使用当前激活的单位
const targets = selectedUnits.length > 0 ? selectedUnits : (activeUnit ? [activeUnit] : []);
// 遍历所有目标单位,调用它们的moveRelative方法进行相对移动
targets.forEach(unit => {
// 确保unit是有效的Unit实例,并且body存在(防止已销毁的单位被调用)
if (unit && typeof unit.moveRelative === 'function' && unit.body) {
unit.moveRelative(dir.x, dir.y);
}
});
}
// 处理移动到指定点的命令
onMoveToPoint(x, y) {
// 确定移动目标单位:优先使用选中的单位列表,如果没有选中单位则使用当前激活的单位
const targets = selectedUnits.length > 0 ? selectedUnits : (activeUnit ? [activeUnit] : []);
// 遍历所有目标单位,调用它们的setTarget方法设置移动目标点
targets.forEach(unit => {
// 确保unit是有效的Unit实例
if (unit && typeof unit.setTarget === 'function') {
unit.setTarget(x, y); // ← 使用单位的新接口方法
}
});
}
// 处理选择单位的命令
onSelectUnit(unit) {
// 动态导入ControlMode.js模块,确保能够访问最新的模块内容
import('./ControlMode.js').then(mod => {
// 调用ControlMode模块的setActiveUnit方法设置当前激活的单位
mod.setActiveUnit(unit);
// 触发'unit-activated'事件,通知其他系统当前单位已激活
this.scene.events.emit('unit-activated', unit);
});
}
}