EnemyController.ts 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  1. import { _decorator, Node, Label, Vec3, Prefab, find, UITransform, resources, RigidBody2D, instantiate } from 'cc';
  2. import { sp } from 'cc';
  3. import { ConfigManager, EnemyConfig } from '../Core/ConfigManager';
  4. import { EnemyComponent } from '../CombatSystem/EnemyComponent';
  5. import { EnemyInstance } from './EnemyInstance';
  6. import { BaseSingleton } from '../Core/BaseSingleton';
  7. import { SaveDataManager } from '../LevelSystem/SaveDataManager';
  8. import { LevelConfigManager } from '../LevelSystem/LevelConfigManager';
  9. import EventBus, { GameEvents } from '../Core/EventBus';
  10. import { Wall } from './Wall';
  11. import { BurnEffect } from './BulletEffects/BurnEffect';
  12. import { Audio } from '../AudioManager/AudioManager';
  13. const { ccclass, property } = _decorator;
  14. @ccclass('EnemyController')
  15. export class EnemyController extends BaseSingleton {
  16. // 仅类型声明,实例由 BaseSingleton 维护
  17. public static _instance: EnemyController;
  18. // 敌人预制体
  19. @property({
  20. type: Prefab,
  21. tooltip: '拖拽Enemy预制体到这里'
  22. })
  23. public enemyPrefab: Prefab = null;
  24. // 敌人容器节点
  25. @property({
  26. type: Node,
  27. tooltip: '拖拽enemyContainer节点到这里(Canvas/GameLevelUI/enemyContainer)'
  28. })
  29. public enemyContainer: Node = null;
  30. // 金币预制体
  31. @property({ type: Prefab, tooltip: '金币预制体 CoinDrop' })
  32. public coinPrefab: Prefab = null;
  33. // 移除Toast预制体属性,改用事件机制
  34. // @property({
  35. // type: Prefab,
  36. // tooltip: 'Toast预制体,用于显示波次提示'
  37. // })
  38. // public toastPrefab: Prefab = null;
  39. // === 生成 & 属性参数(保留需要可在内部自行设定,Inspector 不再显示) ===
  40. private spawnInterval: number = 3;
  41. // === 默认数值(当配置文件尚未加载时使用) ===
  42. private defaultEnemySpeed: number = 50;
  43. private defaultAttackPower: number = 20; // 对应combat.attackDamage
  44. private defaultHealth: number = 10; // 对应stats.health
  45. @property({ type: Node, tooltip: '拖拽 TopFence 节点到这里' })
  46. public topFenceNode: Node = null;
  47. @property({ type: Node, tooltip: '拖拽 BottomFence 节点到这里' })
  48. public bottomFenceNode: Node = null;
  49. // 关卡配置管理器节点
  50. @property({
  51. type: Node,
  52. tooltip: '拖拽Canvas/LevelConfigManager节点到这里,用于获取LevelConfigManager组件'
  53. })
  54. public levelConfigManagerNode: Node = null;
  55. // 主墙体组件
  56. private wallComponent: Wall = null;
  57. // 游戏区域边界 - 改为public,让敌人实例可以访问
  58. public gameBounds = {
  59. left: 0,
  60. right: 0,
  61. top: 0,
  62. bottom: 0
  63. };
  64. // 活跃的敌人列表
  65. private activeEnemies: Node[] = [];
  66. // 游戏是否已开始
  67. private gameStarted: boolean = false;
  68. // 墙体节点
  69. private wallNodes: Node[] = [];
  70. // 是否正在清理敌人(用于阻止清理时触发游戏胜利判断)
  71. private isClearing: boolean = false;
  72. // 配置管理器
  73. private configManager: ConfigManager = null;
  74. // 关卡配置管理器
  75. private levelConfigManager: LevelConfigManager = null;
  76. // 当前关卡血量倍率
  77. private currentHealthMultiplier: number = 1.0;
  78. @property({
  79. type: Node,
  80. tooltip: '敌人数量显示节点 (EnemyNumber)'
  81. })
  82. public enemyCountLabelNode: Node = null;
  83. @property({
  84. type: Node,
  85. tooltip: '当前波数显示Label (WaveNumber-前)'
  86. })
  87. public currentWaveNumberLabelNode: Node = null;
  88. @property({
  89. type: Node,
  90. tooltip: '总波数显示Label (WaveNumber-后)'
  91. })
  92. public totalWaveNumberLabelNode: Node = null;
  93. // 当前波次敌人数据
  94. private totalWaves: number = 1;
  95. private currentWave: number = 1;
  96. private currentWaveTotalEnemies: number = 0;
  97. private currentWaveEnemiesKilled: number = 0;
  98. private currentWaveEnemiesSpawned: number = 0; // 当前波次已生成的敌人数量
  99. private currentWaveEnemyConfigs: any[] = []; // 当前波次的敌人配置列表
  100. // 暂停前保存的敌人状态
  101. private pausedEnemyStates: Map<Node, {
  102. velocity: any,
  103. angularVelocity: number,
  104. isMoving: boolean,
  105. attackTimer: number
  106. }> = new Map();
  107. /**
  108. * BaseSingleton 首次实例化回调
  109. */
  110. protected init() {
  111. // 获取配置管理器实例
  112. this.configManager = ConfigManager.getInstance();
  113. // 获取关卡配置管理器实例
  114. if (this.levelConfigManagerNode) {
  115. this.levelConfigManager = this.levelConfigManagerNode.getComponent(LevelConfigManager) || null;
  116. if (!this.levelConfigManager) {
  117. // LevelConfigManager节点上未找到LevelConfigManager组件
  118. }
  119. } else {
  120. // levelConfigManagerNode未通过装饰器绑定,请在编辑器中拖拽Canvas/LevelConfigManager节点
  121. this.levelConfigManager = null;
  122. }
  123. // 如果没有指定enemyContainer,尝试找到它
  124. if (!this.enemyContainer) {
  125. this.enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  126. if (!this.enemyContainer) {
  127. // 找不到enemyContainer节点,将尝试创建
  128. }
  129. }
  130. // 获取游戏区域边界
  131. this.calculateGameBounds();
  132. // 查找墙体节点和组件
  133. this.findWallNodes();
  134. // 直接通过拖拽节点获取 Wall 组件
  135. if (this.topFenceNode && this.topFenceNode.getComponent(Wall)) {
  136. this.wallComponent = this.topFenceNode.getComponent(Wall);
  137. } else if (this.bottomFenceNode && this.bottomFenceNode.getComponent(Wall)) {
  138. this.wallComponent = this.bottomFenceNode.getComponent(Wall);
  139. } else {
  140. // 未找到墙体组件,将无法处理墙体伤害
  141. }
  142. // 确保enemyContainer节点存在
  143. this.ensureEnemyContainer();
  144. // UI节点已通过装饰器拖拽绑定,无需find查找
  145. if (!this.enemyCountLabelNode) {
  146. // enemyCountLabelNode 未通过装饰器绑定,请在编辑器中拖拽 Canvas-001/TopArea/EnemyNode/EnemyNumber 节点
  147. }
  148. if (!this.currentWaveNumberLabelNode) {
  149. // currentWaveNumberLabelNode 未通过装饰器绑定,请在编辑器中拖拽 Canvas-001/TopArea/WaveInfo/WaveNumber-前 节点
  150. }
  151. if (!this.totalWaveNumberLabelNode) {
  152. // totalWaveNumberLabelNode 未通过装饰器绑定,请在编辑器中拖拽 Canvas-001/TopArea/WaveInfo/WaveNumber-后 节点
  153. }
  154. // 初始化敌人数量显示
  155. this.updateEnemyCountLabel();
  156. // 监听游戏事件
  157. this.setupEventListeners();
  158. }
  159. /**
  160. * 设置事件监听器
  161. */
  162. private setupEventListeners() {
  163. const eventBus = EventBus.getInstance();
  164. // 监听暂停事件
  165. eventBus.on(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
  166. // 监听恢复事件
  167. eventBus.on(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  168. // 监听游戏成功/失败事件
  169. eventBus.on(GameEvents.GAME_SUCCESS, this.onGameEndEvent, this);
  170. eventBus.on(GameEvents.GAME_DEFEAT, this.onGameDefeatEvent, this);
  171. // 监听敌人相关事件
  172. eventBus.on(GameEvents.ENEMY_UPDATE_COUNT, this.onUpdateEnemyCountEvent, this);
  173. eventBus.on(GameEvents.ENEMY_START_WAVE, this.onStartWaveEvent, this);
  174. eventBus.on(GameEvents.ENEMY_START_GAME, this.onStartGameEvent, this);
  175. eventBus.on(GameEvents.ENEMY_SHOW_START_WAVE_PROMPT, this.onShowStartWavePromptEvent, this);
  176. // 监听子弹发射检查事件
  177. eventBus.on(GameEvents.BALL_FIRE_BULLET, this.onBallFireBulletEvent, this);
  178. // 监听获取最近敌人事件
  179. eventBus.on(GameEvents.ENEMY_GET_NEAREST, this.onGetNearestEnemyEvent, this);
  180. // 监听重置敌人控制器事件
  181. eventBus.on(GameEvents.RESET_ENEMY_CONTROLLER, this.onResetEnemyControllerEvent, this);
  182. // 监听重置相关事件
  183. eventBus.on(GameEvents.CLEAR_ALL_GAME_OBJECTS, this.onClearAllGameObjectsEvent, this);
  184. eventBus.on(GameEvents.CLEAR_ALL_ENEMIES, this.onClearAllEnemiesEvent, this);
  185. eventBus.on(GameEvents.RESET_ENEMY_CONTROLLER, this.onResetEnemyControllerEvent, this);
  186. // 监听伤害事件
  187. eventBus.on(GameEvents.APPLY_DAMAGE_TO_ENEMY, this.onApplyDamageToEnemyEvent, this);
  188. // 监听子弹击中敌人事件
  189. eventBus.on(GameEvents.BULLET_HIT_ENEMY, this.onBulletHitEnemyEvent, this);
  190. }
  191. /**
  192. * 获取当前关卡的血量倍率
  193. */
  194. private async getCurrentHealthMultiplier(): Promise<number> {
  195. if (!this.levelConfigManager) {
  196. return 1.0;
  197. }
  198. try {
  199. const saveDataManager = SaveDataManager.getInstance();
  200. const currentLevel = saveDataManager ? saveDataManager.getCurrentLevel() : 1;
  201. const levelConfig = await this.levelConfigManager.getLevelConfig(currentLevel);
  202. if (levelConfig && levelConfig.levelSettings && levelConfig.levelSettings.healthMultiplier) {
  203. return levelConfig.levelSettings.healthMultiplier;
  204. }
  205. } catch (error) {
  206. console.warn('[EnemyController] 获取关卡血量倍率失败:', error);
  207. }
  208. return 1.0;
  209. }
  210. /**
  211. * 处理游戏暂停事件
  212. */
  213. private onGamePauseEvent() {
  214. console.log('[EnemyController] 接收到游戏暂停事件,暂停所有敌人');
  215. this.pauseAllEnemies();
  216. this.pauseSpawning();
  217. }
  218. /**
  219. * 处理游戏恢复事件
  220. */
  221. private onGameResumeEvent() {
  222. console.log('[EnemyController] 接收到游戏恢复事件,恢复所有敌人');
  223. this.resumeAllEnemies();
  224. // 通过事件检查游戏状态,决定是否恢复敌人生成
  225. this.resumeSpawning();
  226. }
  227. /**
  228. * 处理游戏结束事件
  229. */
  230. private onGameEndEvent() {
  231. this.stopGame(false); // 停止游戏但不清除敌人
  232. }
  233. /**
  234. * 处理游戏失败事件
  235. */
  236. private onGameDefeatEvent() {
  237. this.stopGame(true); // 停止游戏并清除所有敌人
  238. //是否是应该此时调用onGameDefeat()方法?
  239. }
  240. /**
  241. * 处理清除所有游戏对象事件
  242. */
  243. private onClearAllGameObjectsEvent() {
  244. this.clearAllEnemies(false); // 清除敌人但不触发事件
  245. }
  246. /**
  247. * 处理清除所有敌人事件
  248. * 专门响应CLEAR_ALL_ENEMIES事件,用于游戏结束时的敌人清理
  249. */
  250. private onClearAllEnemiesEvent() {
  251. console.log('[EnemyController] 接收到CLEAR_ALL_ENEMIES事件,开始清理所有敌人');
  252. this.clearAllEnemies(false); // 清除敌人但不触发事件,避免循环
  253. }
  254. /**
  255. * 处理重置敌人控制器事件
  256. */
  257. private onResetEnemyControllerEvent() {
  258. this.resetToInitialState();
  259. }
  260. /**
  261. * 处理子弹发射检查事件
  262. */
  263. private onBallFireBulletEvent(data: { canFire: (value: boolean) => void }) {
  264. // 检查是否有活跃敌人
  265. const hasActiveEnemies = this.hasActiveEnemies();
  266. data.canFire(hasActiveEnemies);
  267. }
  268. /**
  269. * 处理获取最近敌人事件
  270. */
  271. private onGetNearestEnemyEvent(data: { position: Vec3, callback: (enemy: Node | null) => void }) {
  272. const { position, callback } = data;
  273. if (callback && typeof callback === 'function') {
  274. const nearestEnemy = this.getNearestEnemy(position);
  275. callback(nearestEnemy);
  276. }
  277. }
  278. /**
  279. * 处理对敌人造成伤害事件
  280. */
  281. private onApplyDamageToEnemyEvent(data: { enemyNode: Node, damage: number, isCritical: boolean, source: string }) {
  282. console.log(`[EnemyController] 接收到伤害事件 - 敌人: ${data.enemyNode.name}, 伤害: ${data.damage}, 暴击: ${data.isCritical}, 来源: ${data.source}`);
  283. if (!data.enemyNode || !data.enemyNode.isValid) {
  284. console.log(`[EnemyController] 敌人节点无效,跳过伤害处理`);
  285. return;
  286. }
  287. // 调用现有的damageEnemy方法
  288. this.damageEnemy(data.enemyNode, data.damage, data.isCritical);
  289. }
  290. /**
  291. * 处理子弹击中敌人事件
  292. */
  293. private onBulletHitEnemyEvent(data: { enemyNode: Node, damage: number, isCritical: boolean, source: string }) {
  294. console.log(`[EnemyController] 接收到子弹击中敌人事件 - 敌人: ${data.enemyNode.name}, 伤害: ${data.damage}, 暴击: ${data.isCritical}, 来源: ${data.source}`);
  295. if (!data.enemyNode || !data.enemyNode.isValid) {
  296. console.log(`[EnemyController] 敌人节点无效,跳过伤害处理`);
  297. return;
  298. }
  299. // 调用现有的damageEnemy方法
  300. this.damageEnemy(data.enemyNode, data.damage, data.isCritical);
  301. }
  302. /**
  303. * 暂停所有敌人
  304. */
  305. private pauseAllEnemies(): void {
  306. const activeEnemies = this.getActiveEnemies();
  307. console.log(`[EnemyController] 暂停 ${activeEnemies.length} 个敌人`);
  308. for (const enemy of activeEnemies) {
  309. if (!enemy || !enemy.isValid) continue;
  310. // 保存敌人状态 - 从EnemySprite子节点获取RigidBody2D
  311. const enemySprite = enemy.getChildByName('EnemySprite');
  312. if (!enemySprite) {
  313. console.error('[EnemyController] pauseAllEnemies: 未找到EnemySprite子节点');
  314. continue;
  315. }
  316. const rigidBody = enemySprite.getComponent(RigidBody2D);
  317. if (rigidBody) {
  318. this.pausedEnemyStates.set(enemy, {
  319. velocity: rigidBody.linearVelocity.clone(),
  320. angularVelocity: rigidBody.angularVelocity,
  321. isMoving: true,
  322. attackTimer: 0 // 可以扩展保存攻击计时器
  323. });
  324. // 停止敌人运动
  325. rigidBody.linearVelocity.set(0, 0);
  326. rigidBody.angularVelocity = 0;
  327. rigidBody.sleep();
  328. }
  329. // 暂停EnemyInstance组件
  330. const enemyInstance = enemy.getComponent('EnemyInstance');
  331. if (enemyInstance && typeof (enemyInstance as any).pause === 'function') {
  332. (enemyInstance as any).pause();
  333. }
  334. // 暂停敌人AI组件(如果有的话)
  335. const enemyAI = enemy.getComponent('EnemyAI');
  336. if (enemyAI && typeof (enemyAI as any).pause === 'function') {
  337. (enemyAI as any).pause();
  338. }
  339. // 暂停敌人动画(如果有的话)
  340. const animation = enemy.getComponent('Animation');
  341. if (animation && typeof (animation as any).pause === 'function') {
  342. (animation as any).pause();
  343. }
  344. }
  345. }
  346. /**
  347. * 恢复所有敌人
  348. */
  349. private resumeAllEnemies(): void {
  350. const activeEnemies = this.getActiveEnemies();
  351. for (const enemy of activeEnemies) {
  352. if (!enemy || !enemy.isValid) continue;
  353. const savedState = this.pausedEnemyStates.get(enemy);
  354. if (savedState) {
  355. // 从EnemySprite子节点获取RigidBody2D
  356. const enemySprite = enemy.getChildByName('EnemySprite');
  357. if (!enemySprite) {
  358. console.error('[EnemyController] resumeAllEnemies: 未找到EnemySprite子节点');
  359. continue;
  360. }
  361. const rigidBody = enemySprite.getComponent(RigidBody2D);
  362. if (rigidBody) {
  363. // 恢复敌人运动
  364. rigidBody.wakeUp();
  365. rigidBody.linearVelocity = savedState.velocity;
  366. rigidBody.angularVelocity = savedState.angularVelocity;
  367. }
  368. }
  369. // 恢复EnemyInstance组件
  370. const enemyInstance = enemy.getComponent('EnemyInstance');
  371. if (enemyInstance && typeof (enemyInstance as any).resume === 'function') {
  372. (enemyInstance as any).resume();
  373. }
  374. // 恢复敌人AI组件
  375. const enemyAI = enemy.getComponent('EnemyAI');
  376. if (enemyAI && typeof (enemyAI as any).resume === 'function') {
  377. (enemyAI as any).resume();
  378. }
  379. // 恢复敌人动画
  380. const animation = enemy.getComponent('Animation');
  381. if (animation && typeof (animation as any).resume === 'function') {
  382. (animation as any).resume();
  383. }
  384. }
  385. // 清空保存的状态
  386. this.pausedEnemyStates.clear();
  387. }
  388. // 计算游戏区域边界
  389. private calculateGameBounds() {
  390. const gameArea = find('Canvas/GameLevelUI/GameArea');
  391. if (!gameArea) {
  392. return;
  393. }
  394. const uiTransform = gameArea.getComponent(UITransform);
  395. if (!uiTransform) {
  396. return;
  397. }
  398. const worldPos = gameArea.worldPosition;
  399. const width = uiTransform.width;
  400. const height = uiTransform.height;
  401. this.gameBounds = {
  402. left: worldPos.x - width / 2,
  403. right: worldPos.x + width / 2,
  404. top: worldPos.y + height / 2,
  405. bottom: worldPos.y - height / 2
  406. };
  407. }
  408. // 查找墙体节点
  409. private findWallNodes() {
  410. const gameArea = find('Canvas/GameLevelUI/GameArea');
  411. if (gameArea) {
  412. this.wallNodes = [];
  413. for (let i = 0; i < gameArea.children.length; i++) {
  414. const child = gameArea.children[i];
  415. if (child.name.includes('Wall') || child.name.includes('wall') || child.name.includes('墙')) {
  416. this.wallNodes.push(child);
  417. }
  418. }
  419. }
  420. }
  421. /**
  422. * 查找墙体组件
  423. */
  424. private findWallComponent() {
  425. // 查找墙体节点上的Wall组件
  426. for (const wallNode of this.wallNodes) {
  427. this.wallComponent = wallNode.getComponent(Wall);
  428. if (this.wallComponent) {
  429. break;
  430. }
  431. }
  432. }
  433. // 移除 initWallHealthDisplay 和 updateWallHealthDisplay 方法,这些现在由Wall组件处理
  434. // 确保enemyContainer节点存在
  435. ensureEnemyContainer() {
  436. // 如果已经通过拖拽设置了节点,直接使用
  437. if (this.enemyContainer && this.enemyContainer.isValid) {
  438. return;
  439. }
  440. // 尝试查找节点
  441. this.enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  442. if (this.enemyContainer) {
  443. return;
  444. }
  445. // 如果找不到,创建新节点
  446. const gameLevelUI = find('Canvas/GameLevelUI');
  447. if (!gameLevelUI) {
  448. console.error('找不到GameLevelUI节点,无法创建enemyContainer');
  449. return;
  450. }
  451. this.enemyContainer = new Node('enemyContainer');
  452. gameLevelUI.addChild(this.enemyContainer);
  453. if (!this.enemyContainer.getComponent(UITransform)) {
  454. this.enemyContainer.addComponent(UITransform);
  455. }
  456. }
  457. // 游戏开始
  458. startGame() {
  459. // 游戏状态检查现在通过事件系统处理
  460. this.gameStarted = true;
  461. // 确保enemyContainer节点存在
  462. this.ensureEnemyContainer();
  463. // 确保先取消之前的定时器,避免重复调度
  464. this.unschedule(this.spawnEnemy);
  465. // 播放游戏开始音效
  466. Audio.playUISound('data/弹球音效/start zombie');
  467. // 立即生成第一个敌人,与音效同步
  468. this.spawnEnemy();
  469. // 然后按间隔生成后续敌人
  470. this.schedule(this.spawnEnemy, this.spawnInterval);
  471. // 触发敌人生成开始事件
  472. const eventBus = EventBus.getInstance();
  473. eventBus.emit(GameEvents.ENEMY_SPAWNING_STARTED);
  474. }
  475. // 游戏结束
  476. stopGame(clearEnemies: boolean = true) {
  477. this.gameStarted = false;
  478. // 停止生成敌人
  479. this.unschedule(this.spawnEnemy);
  480. // 触发敌人生成停止事件
  481. const eventBus = EventBus.getInstance();
  482. eventBus.emit(GameEvents.ENEMY_SPAWNING_STOPPED);
  483. // 只有在指定时才清除所有敌人
  484. if (clearEnemies) {
  485. // 清除敌人,在重置状态时不触发事件,避免错误的游戏成功判定
  486. this.clearAllEnemies(false);
  487. }
  488. }
  489. // 生成敌人
  490. async spawnEnemy() {
  491. if (!this.gameStarted || !this.enemyPrefab) {
  492. return;
  493. }
  494. // 游戏状态检查现在通过事件系统处理
  495. // 检查是否已达到当前波次的敌人生成上限
  496. if (this.currentWaveEnemiesSpawned >= this.currentWaveTotalEnemies) {
  497. this.unschedule(this.spawnEnemy); // 停止定时生成
  498. return;
  499. }
  500. // 随机决定从上方还是下方生成
  501. const fromTop = Math.random() > 0.5;
  502. // 实例化敌人
  503. const enemy = instantiate(this.enemyPrefab) as Node;
  504. enemy.name = 'Enemy'; // 确保敌人节点名称为Enemy
  505. // 添加到场景中
  506. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  507. if (!enemyContainer) {
  508. return;
  509. }
  510. enemyContainer.addChild(enemy);
  511. // 生成在对应线(Line1 / Line2)上的随机位置
  512. const lineName = fromTop ? 'Line1' : 'Line2';
  513. const lineNode = enemyContainer.getChildByName(lineName);
  514. if (!lineNode) {
  515. console.warn(`[EnemyController] 未找到 ${lineName} 节点,取消本次敌人生成`);
  516. enemy.destroy();
  517. return;
  518. }
  519. // 在对应 line 上随机 X 坐标
  520. const spawnWorldX = this.gameBounds.left + Math.random() * (this.gameBounds.right - this.gameBounds.left);
  521. const spawnWorldY = lineNode.worldPosition.y;
  522. const worldPos = new Vec3(spawnWorldX, spawnWorldY, 0);
  523. const localPos = enemyContainer.getComponent(UITransform).convertToNodeSpaceAR(worldPos);
  524. enemy.position = localPos;
  525. // === 根据配置设置敌人 ===
  526. const enemyComp = enemy.addComponent(EnemyInstance);
  527. // 确保敌人数据库已加载
  528. await EnemyInstance.loadEnemyDatabase();
  529. let enemyConfig: EnemyConfig = null;
  530. let enemyId: string = null;
  531. if (this.configManager && this.configManager.isConfigLoaded()) {
  532. // 优先使用当前波次配置中的敌人类型
  533. if (this.currentWaveEnemyConfigs.length > 0) {
  534. const configIndex = this.currentWaveEnemiesSpawned % this.currentWaveEnemyConfigs.length;
  535. const enemyTypeConfig = this.currentWaveEnemyConfigs[configIndex];
  536. const enemyType = enemyTypeConfig.enemyType || enemyTypeConfig;
  537. // enemyType本身就是敌人ID,直接使用
  538. enemyId = enemyType;
  539. console.log(`[EnemyController] 使用敌人类型: ${enemyType} 作为敌人ID`);
  540. enemyConfig = this.configManager.getEnemyById(enemyId) || this.configManager.getRandomEnemy();
  541. } else {
  542. enemyConfig = this.configManager.getRandomEnemy();
  543. enemyId = enemyConfig?.id || 'normal_zombie';
  544. }
  545. }
  546. // 获取当前关卡的血量倍率
  547. const healthMultiplier = await this.getCurrentHealthMultiplier();
  548. if (enemyConfig && enemyId) {
  549. try {
  550. const cfgComp = enemy.addComponent(EnemyComponent);
  551. cfgComp.enemyConfig = enemyConfig;
  552. cfgComp.spawner = this;
  553. } catch (error) {
  554. console.error(`[EnemyController] 添加EnemyComponent失败:`, error);
  555. }
  556. // 使用EnemyInstance的新配置系统
  557. try {
  558. // 设置敌人配置
  559. enemyComp.setEnemyConfig(enemyId);
  560. // 应用血量倍率
  561. const baseHealth = enemyComp.health || this.defaultHealth;
  562. const finalHealth = Math.round(baseHealth * healthMultiplier);
  563. enemyComp.health = finalHealth;
  564. enemyComp.maxHealth = finalHealth;
  565. console.log(`[EnemyController] 敌人 ${enemyId} 配置已应用,血量: ${finalHealth}`);
  566. } catch (error) {
  567. console.error(`[EnemyController] 应用敌人配置时出错:`, error);
  568. // 使用默认值
  569. const finalHealth = Math.round(this.defaultHealth * healthMultiplier);
  570. enemyComp.health = finalHealth;
  571. enemyComp.maxHealth = finalHealth;
  572. enemyComp.speed = this.defaultEnemySpeed;
  573. enemyComp.attackPower = this.defaultAttackPower;
  574. }
  575. // 加载动画
  576. this.loadEnemyAnimation(enemy, enemyConfig);
  577. } else {
  578. // 使用默认配置
  579. try {
  580. enemyComp.setEnemyConfig('normal_zombie'); // 默认敌人类型
  581. const baseHealth = enemyComp.health || this.defaultHealth;
  582. const finalHealth = Math.round(baseHealth * healthMultiplier);
  583. enemyComp.health = finalHealth;
  584. enemyComp.maxHealth = finalHealth;
  585. } catch (error) {
  586. console.error(`[EnemyController] 应用默认敌人配置时出错:`, error);
  587. // 使用硬编码默认值
  588. const finalHealth = Math.round(this.defaultHealth * healthMultiplier);
  589. enemyComp.health = finalHealth;
  590. enemyComp.maxHealth = finalHealth;
  591. enemyComp.speed = this.defaultEnemySpeed;
  592. enemyComp.attackPower = this.defaultAttackPower;
  593. }
  594. }
  595. // 额外的属性设置
  596. enemyComp.spawnFromTop = fromTop;
  597. enemyComp.targetFence = find(fromTop ? 'Canvas/GameLevelUI/GameArea/TopFence' : 'Canvas/GameLevelUI/GameArea/BottomFence');
  598. enemyComp.movingDirection = Math.random() > 0.5 ? 1 : -1;
  599. enemyComp.targetY = fromTop ? this.gameBounds.top - 50 : this.gameBounds.bottom + 50;
  600. enemyComp.changeDirectionTime = 0;
  601. enemyComp.controller = this;
  602. // 更新敌人血量显示
  603. enemyComp.updateHealthDisplay();
  604. // 添加到活跃敌人列表
  605. this.activeEnemies.push(enemy);
  606. // 增加已生成敌人计数
  607. this.currentWaveEnemiesSpawned++;
  608. // 生成敌人时不更新敌人数量显示,避免重置计数
  609. }
  610. // 清除所有敌人
  611. clearAllEnemies(triggerEvents: boolean = true) {
  612. // 设置清理标志,阻止清理过程中触发游戏胜利判断
  613. if (!triggerEvents) {
  614. this.isClearing = true;
  615. }
  616. // 如果不触发事件,先暂时禁用 notifyEnemyDead 方法
  617. const originalNotifyMethod = this.notifyEnemyDead;
  618. if (!triggerEvents) {
  619. // 临时替换为空函数
  620. this.notifyEnemyDead = () => {};
  621. }
  622. for (const enemy of this.activeEnemies) {
  623. if (enemy && enemy.isValid) {
  624. enemy.destroy();
  625. }
  626. }
  627. // 恢复原来的方法
  628. if (!triggerEvents) {
  629. this.notifyEnemyDead = originalNotifyMethod;
  630. }
  631. this.activeEnemies = [];
  632. // 重置清理标志
  633. if (!triggerEvents) {
  634. this.isClearing = false;
  635. }
  636. // 清除敌人时不更新敌人数量显示,避免重置计数
  637. }
  638. // 获取所有活跃的敌人
  639. getActiveEnemies(): Node[] {
  640. // 过滤掉已经无效的敌人
  641. this.activeEnemies = this.activeEnemies.filter(enemy => enemy && enemy.isValid);
  642. return this.activeEnemies;
  643. }
  644. // 获取当前敌人数量
  645. getCurrentEnemyCount(): number {
  646. return this.getActiveEnemies().length;
  647. }
  648. // 获取最近的敌人节点
  649. public getNearestEnemy(fromPosition: Vec3): Node | null {
  650. const enemies = this.getActiveEnemies();
  651. if (enemies.length === 0) return null;
  652. let nearestEnemy: Node = null;
  653. let nearestDistance = Infinity;
  654. for (const enemy of enemies) {
  655. const distance = Vec3.distance(fromPosition, enemy.worldPosition);
  656. if (distance < nearestDistance) {
  657. nearestDistance = distance;
  658. nearestEnemy = enemy;
  659. }
  660. }
  661. return nearestEnemy;
  662. }
  663. // 检查是否有活跃敌人
  664. public hasActiveEnemies(): boolean {
  665. const activeCount = this.getActiveEnemies().length;
  666. return activeCount > 0;
  667. }
  668. // 调试方法:检查enemyContainer中的实际敌人节点
  669. private debugEnemyContainer() {
  670. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  671. if (!enemyContainer) {
  672. return;
  673. }
  674. let enemyNodeCount = 0;
  675. enemyContainer.children.forEach((child, index) => {
  676. if (child.name === 'Enemy' || child.name.includes('Enemy')) {
  677. enemyNodeCount++;
  678. }
  679. });
  680. }
  681. // 调试方法:强制清理无效敌人引用
  682. public debugCleanupEnemies() {
  683. const beforeCount = this.activeEnemies.length;
  684. this.activeEnemies = this.activeEnemies.filter(enemy => enemy && enemy.isValid);
  685. const afterCount = this.activeEnemies.length;
  686. return afterCount;
  687. }
  688. // 获取游戏是否已开始状态
  689. public isGameStarted(): boolean {
  690. return this.gameStarted;
  691. }
  692. // 暂停生成敌人
  693. public pauseSpawning(): void {
  694. if (this.gameStarted) {
  695. this.unschedule(this.spawnEnemy);
  696. // 触发敌人生成停止事件
  697. const eventBus = EventBus.getInstance();
  698. eventBus.emit(GameEvents.ENEMY_SPAWNING_STOPPED);
  699. }
  700. }
  701. // 恢复生成敌人
  702. public resumeSpawning(): void {
  703. // 游戏状态检查现在通过事件系统处理
  704. if (!this.gameStarted) {
  705. return;
  706. }
  707. // 检查是否已达到当前波次的敌人生成上限
  708. if (this.currentWaveEnemiesSpawned >= this.currentWaveTotalEnemies) {
  709. return;
  710. }
  711. // 确保先取消之前的定时器,避免重复调度
  712. this.unschedule(this.spawnEnemy);
  713. this.schedule(this.spawnEnemy, this.spawnInterval);
  714. // 触发敌人生成开始事件
  715. const eventBus = EventBus.getInstance();
  716. eventBus.emit(GameEvents.ENEMY_SPAWNING_STARTED);
  717. }
  718. // 敌人受到伤害
  719. damageEnemy(enemy: Node, damage: number, isCritical: boolean = false) {
  720. if (!enemy || !enemy.isValid) return;
  721. // 游戏状态检查现在通过事件系统处理
  722. // 获取敌人组件
  723. const enemyComp = enemy.getComponent(EnemyInstance);
  724. if (!enemyComp) return;
  725. // 减少敌人血量
  726. enemyComp.takeDamage(damage, isCritical);
  727. // 检查敌人是否死亡
  728. if (enemyComp.health <= 0) {
  729. // 从活跃敌人列表中移除
  730. const index = this.activeEnemies.indexOf(enemy);
  731. if (index !== -1) {
  732. this.activeEnemies.splice(index, 1);
  733. }
  734. // 清理敌人身上的所有灼烧效果,防止定时器继续运行
  735. try {
  736. const burnEffect = enemy.getComponent(BurnEffect);
  737. if (burnEffect) {
  738. console.log(`[EnemyController] 清理敌人身上的灼烧效果`);
  739. // 先停止灼烧效果,再移除组件
  740. burnEffect.stopBurnEffect();
  741. enemy.removeComponent(BurnEffect);
  742. }
  743. } catch (error) {
  744. console.warn(`[EnemyController] 清理灼烧效果时出错:`, error);
  745. }
  746. // 敌人死亡时不在这里更新数量显示,由GameManager统一管理
  747. // 延迟销毁敌人,避免在物理碰撞监听器中直接销毁导致的刚体激活错误
  748. this.scheduleOnce(() => {
  749. if (enemy && enemy.isValid) {
  750. enemy.destroy();
  751. }
  752. }, 0);
  753. }
  754. }
  755. // 墙体受到伤害 - 现在委托给Wall组件
  756. damageWall(damage: number) {
  757. if (this.wallComponent) {
  758. this.wallComponent.takeDamage(damage);
  759. } else {
  760. console.warn('[EnemyController] 墙体组件未找到,无法处理伤害');
  761. }
  762. }
  763. // 游戏结束
  764. gameOver() {
  765. // 停止游戏,但不清除敌人
  766. this.stopGame(false);
  767. // 通过事件系统触发游戏失败
  768. const eventBus = EventBus.getInstance();
  769. eventBus.emit(GameEvents.GAME_DEFEAT);
  770. }
  771. update(dt: number) {
  772. if (!this.gameStarted) return;
  773. // 更新所有敌人
  774. for (let i = this.activeEnemies.length - 1; i >= 0; i--) {
  775. const enemy = this.activeEnemies[i];
  776. if (!enemy || !enemy.isValid) {
  777. this.activeEnemies.splice(i, 1);
  778. continue;
  779. }
  780. // 敌人更新由各自的组件处理
  781. // 不再需要检查敌人是否到达墙体,因为敌人到达游戏区域后会自动攻击
  782. // 敌人的攻击逻辑已经在EnemyInstance中处理
  783. }
  784. }
  785. public getCurrentWallHealth(): number {
  786. return this.wallComponent ? this.wallComponent.getCurrentHealth() : 0;
  787. }
  788. public forceEnemyAttack() {
  789. const activeEnemies = this.getActiveEnemies();
  790. for (const enemy of activeEnemies) {
  791. const enemyComp = enemy.getComponent(EnemyInstance);
  792. if (enemyComp) {
  793. // 直接调用damageWall方法进行测试
  794. this.damageWall(enemyComp.attackPower);
  795. }
  796. }
  797. }
  798. /** 供 EnemyInstance 在 onDestroy 中调用 */
  799. public notifyEnemyDead(enemyNode?: Node) {
  800. // 如果正在清理敌人,不触发任何游戏事件
  801. if (this.isClearing) {
  802. if (enemyNode) {
  803. const idx = this.activeEnemies.indexOf(enemyNode);
  804. if (idx !== -1) {
  805. this.activeEnemies.splice(idx, 1);
  806. }
  807. }
  808. return;
  809. }
  810. if (enemyNode) {
  811. const idx = this.activeEnemies.indexOf(enemyNode);
  812. if (idx !== -1) {
  813. this.activeEnemies.splice(idx, 1);
  814. } else {
  815. console.log(`[EnemyController] 警告:尝试移除的敌人不在activeEnemies数组中!`);
  816. }
  817. // 移除EnemyController内部的击杀计数,统一由GameManager管理
  818. // this.currentWaveEnemiesKilled++;
  819. // 敌人死亡通知时不更新数量显示,由GameManager统一管理
  820. }
  821. // 直接通过事件总线发送ENEMY_KILLED事件,避免通过GamePause的双重调用
  822. const eventBus = EventBus.getInstance();
  823. eventBus.emit('ENEMY_KILLED');
  824. }
  825. /**
  826. * 加载敌人骨骼动画
  827. */
  828. private loadEnemyAnimation(enemyNode: Node, enemyConfig: EnemyConfig) {
  829. console.log(`[EnemyController] 开始加载敌人动画,敌人ID: ${enemyConfig?.id}, 敌人名称: ${enemyConfig?.name}`);
  830. if (!enemyConfig || !enemyConfig.visualConfig) {
  831. console.warn('[EnemyController] 敌人配置或视觉配置缺失,使用默认动画');
  832. return;
  833. }
  834. let spinePath: string | undefined = enemyConfig.visualConfig?.spritePath;
  835. console.log(`[EnemyController] 敌人 ${enemyConfig.id} 的spritePath: ${spinePath}`);
  836. if (!spinePath) {
  837. console.warn('[EnemyController] 敌人精灵路径缺失');
  838. return;
  839. }
  840. if (spinePath.startsWith('@EnemyAni')) {
  841. spinePath = spinePath.replace('@EnemyAni', 'Animation/EnemyAni');
  842. }
  843. if (spinePath.startsWith('@')) {
  844. spinePath = spinePath.substring(1);
  845. }
  846. // 对于Animation/EnemyAni路径,需要添加子目录和文件名
  847. // 例如:Animation/EnemyAni/007 -> Animation/EnemyAni/007/007
  848. if (spinePath.startsWith('Animation/EnemyAni/')) {
  849. const parts = spinePath.split('/');
  850. if (parts.length === 3) {
  851. const animId = parts[2];
  852. spinePath = `${spinePath}/${animId}`;
  853. }
  854. }
  855. console.log(`[EnemyController] 最终加载路径: ${spinePath}`);
  856. resources.load(spinePath, sp.SkeletonData, (err, skeletonData) => {
  857. if (err) {
  858. console.warn(`加载敌人Spine动画失败: ${spinePath}`, err);
  859. return;
  860. }
  861. // 获取EnemySprite子节点
  862. const enemySprite = enemyNode.getChildByName('EnemySprite');
  863. if (!enemySprite) {
  864. console.error('[EnemyController] 未找到EnemySprite子节点,无法设置骨骼动画');
  865. return;
  866. }
  867. let skeleton = enemySprite.getComponent(sp.Skeleton);
  868. if (!skeleton) {
  869. skeleton = enemySprite.addComponent(sp.Skeleton);
  870. }
  871. skeleton.skeletonData = skeletonData;
  872. const anims = enemyConfig.visualConfig.animations;
  873. const walkName = anims?.walk ?? 'walk';
  874. const idleName = anims?.idle ?? 'idle';
  875. if (skeleton.findAnimation(walkName)) {
  876. skeleton.setAnimation(0, walkName, true);
  877. } else if (skeleton.findAnimation(idleName)) {
  878. skeleton.setAnimation(0, idleName, true);
  879. } else {
  880. console.warn(`[EnemyController] 未找到合适的动画,walk: ${walkName}, idle: ${idleName}`);
  881. }
  882. });
  883. }
  884. // 更新敌人数量显示
  885. public updateEnemyCountLabel(killedCount?: number) {
  886. if (!this.enemyCountLabelNode) {
  887. console.warn('[EnemyController] enemyCountLabelNode 未找到,无法更新敌人数量显示');
  888. return;
  889. }
  890. const label = this.enemyCountLabelNode.getComponent(Label);
  891. if (label) {
  892. // 计算剩余敌人数量:总数 - 击杀数量
  893. let remaining: number;
  894. if (killedCount !== undefined) {
  895. // 使用传入的击杀数量计算剩余数量
  896. remaining = Math.max(0, this.currentWaveTotalEnemies - killedCount);
  897. } else {
  898. // 如果没有传入击杀数量,则显示当前波次总敌人数(初始状态)
  899. remaining = this.currentWaveTotalEnemies;
  900. }
  901. label.string = remaining.toString();
  902. } else {
  903. console.warn('[EnemyController] enemyCountLabelNode 上未找到 Label 组件');
  904. }
  905. }
  906. public startWave(waveNum: number, totalWaves: number, totalEnemies: number, waveEnemyConfigs?: any[]) {
  907. this.currentWave = waveNum;
  908. this.totalWaves = totalWaves;
  909. this.currentWaveTotalEnemies = totalEnemies;
  910. this.currentWaveEnemiesSpawned = 0; // 重置已生成敌人计数器
  911. this.currentWaveEnemyConfigs = waveEnemyConfigs || []; // 存储当前波次的敌人配置
  912. // 移除EnemyController内部的击杀计数重置,统一由GameManager管理
  913. // this.currentWaveEnemiesKilled = 0;
  914. // 修复问题1:根据波次配置设置生成间隔
  915. if (this.currentWaveEnemyConfigs.length > 0) {
  916. // 使用第一个敌人配置的spawnInterval,如果有多个配置可以取平均值或最小值
  917. const firstEnemyConfig = this.currentWaveEnemyConfigs[0];
  918. if (firstEnemyConfig && typeof firstEnemyConfig.spawnInterval === 'number') {
  919. this.spawnInterval = firstEnemyConfig.spawnInterval;
  920. console.log(`[EnemyController] 设置生成间隔为: ${this.spawnInterval}`);
  921. }
  922. }
  923. console.log(`[EnemyController] 开始波次 ${waveNum}/${totalWaves},需要生成 ${totalEnemies} 个敌人`);
  924. console.log(`[EnemyController] 波次敌人配置:`, this.currentWaveEnemyConfigs);
  925. console.log(`[EnemyController] 当前生成间隔: ${this.spawnInterval}`);
  926. this.updateWaveLabel();
  927. this.updateEnemyCountLabel();
  928. // 移除startWaveUI的隐藏,因为现在使用Toast预制体
  929. // if (this.startWaveUI) this.startWaveUI.active = false;
  930. }
  931. private updateWaveLabel() {
  932. // 更新当前波数显示
  933. if (this.currentWaveNumberLabelNode) {
  934. const currentLabel = this.currentWaveNumberLabelNode.getComponent(Label);
  935. if (currentLabel) {
  936. currentLabel.string = this.currentWave.toString();
  937. } else {
  938. console.warn('[EnemyController] currentWaveNumberLabelNode 上未找到 Label 组件');
  939. }
  940. } else {
  941. console.warn('[EnemyController] currentWaveNumberLabelNode 未找到,无法更新当前波次标签');
  942. }
  943. // 更新总波数显示
  944. if (this.totalWaveNumberLabelNode) {
  945. const totalLabel = this.totalWaveNumberLabelNode.getComponent(Label);
  946. if (totalLabel) {
  947. totalLabel.string = this.totalWaves.toString();
  948. } else {
  949. console.warn('[EnemyController] totalWaveNumberLabelNode 上未找到 Label 组件');
  950. }
  951. } else {
  952. console.warn('[EnemyController] totalWaveNumberLabelNode 未找到,无法更新总波次标签');
  953. }
  954. }
  955. /** 显示每波开始提示,随后开启敌人生成 */
  956. public showStartWavePromptUI(duration: number = 2) {
  957. // 通过事件系统检查游戏是否已经结束
  958. let gameOver = false;
  959. EventBus.getInstance().emit(GameEvents.GAME_CHECK_OVER, (isOver: boolean) => {
  960. gameOver = isOver;
  961. });
  962. if (gameOver) {
  963. return;
  964. }
  965. // 暂停敌人生成,确保在Toast显示期间不会生成敌人
  966. this.pauseSpawning();
  967. // 使用事件机制显示Toast
  968. const toastText = `第${this.currentWave}波敌人来袭!`;
  969. EventBus.getInstance().emit(GameEvents.SHOW_TOAST, {
  970. message: toastText,
  971. duration: duration
  972. });
  973. // 等待Toast消息播放结束后再开始生成敌人
  974. if (duration > 0) {
  975. this.scheduleOnce(() => {
  976. // 再次检查游戏状态,确保游戏未结束
  977. let gameOverCheck = false;
  978. EventBus.getInstance().emit(GameEvents.GAME_CHECK_OVER, (isOver: boolean) => {
  979. gameOverCheck = isOver;
  980. });
  981. if (gameOverCheck) {
  982. return;
  983. }
  984. // Toast播放完毕,开始生成敌人
  985. this.startGame();
  986. }, duration);
  987. } else {
  988. // 如果duration为0,立即开始游戏
  989. this.startGame();
  990. }
  991. }
  992. /**
  993. * 重置到初始状态
  994. * 用于游戏重新开始时重置所有敌人相关状态
  995. */
  996. public resetToInitialState(): void {
  997. // 停止游戏并清理所有敌人
  998. this.stopGame(true);
  999. // 重置波次信息
  1000. this.currentWave = 1;
  1001. this.totalWaves = 1;
  1002. this.currentWaveTotalEnemies = 0;
  1003. this.currentWaveEnemiesKilled = 0;
  1004. this.currentWaveEnemiesSpawned = 0;
  1005. this.currentWaveEnemyConfigs = [];
  1006. // 重置血量倍率
  1007. this.currentHealthMultiplier = 1.0;
  1008. // 清空暂停状态
  1009. this.pausedEnemyStates.clear();
  1010. // 重置UI显示
  1011. this.updateEnemyCountLabel();
  1012. this.updateWaveLabel();
  1013. }
  1014. /**
  1015. * 处理更新敌人计数事件
  1016. */
  1017. private onUpdateEnemyCountEvent(killedCount: number) {
  1018. this.updateEnemyCountLabel(killedCount);
  1019. }
  1020. /**
  1021. * 处理启动波次事件
  1022. */
  1023. private onStartWaveEvent(data: { wave: number; totalWaves: number; enemyCount: number; waveEnemyConfigs: any[] }) {
  1024. this.startWave(data.wave, data.totalWaves, data.enemyCount, data.waveEnemyConfigs);
  1025. }
  1026. /**
  1027. * 处理启动游戏事件
  1028. */
  1029. private onStartGameEvent() {
  1030. this.startGame();
  1031. }
  1032. /**
  1033. * 处理显示波次提示事件
  1034. */
  1035. private onShowStartWavePromptEvent() {
  1036. this.showStartWavePromptUI();
  1037. }
  1038. onDestroy() {
  1039. // 清理事件监听
  1040. const eventBus = EventBus.getInstance();
  1041. eventBus.off(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
  1042. eventBus.off(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  1043. eventBus.off(GameEvents.GAME_SUCCESS, this.onGameEndEvent, this);
  1044. eventBus.off(GameEvents.GAME_DEFEAT, this.onGameEndEvent, this);
  1045. eventBus.off(GameEvents.CLEAR_ALL_GAME_OBJECTS, this.onClearAllGameObjectsEvent, this);
  1046. eventBus.off(GameEvents.CLEAR_ALL_ENEMIES, this.onClearAllEnemiesEvent, this);
  1047. eventBus.off(GameEvents.RESET_ENEMY_CONTROLLER, this.onResetEnemyControllerEvent, this);
  1048. // 清理新增的事件监听
  1049. eventBus.off(GameEvents.ENEMY_UPDATE_COUNT, this.onUpdateEnemyCountEvent, this);
  1050. eventBus.off(GameEvents.ENEMY_START_WAVE, this.onStartWaveEvent, this);
  1051. eventBus.off(GameEvents.ENEMY_START_GAME, this.onStartGameEvent, this);
  1052. eventBus.off(GameEvents.ENEMY_SHOW_START_WAVE_PROMPT, this.onShowStartWavePromptEvent, this);
  1053. // 清空状态
  1054. this.pausedEnemyStates.clear();
  1055. }
  1056. }