EnemyController.ts 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  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. // 随机选择从Line1或Line2生成
  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. // 根据随机选择生成在对应线上的随机位置
  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. // 在对应线上随机 X 坐标
  520. const spawnWorldX = this.gameBounds.left + Math.random() * (this.gameBounds.right - this.gameBounds.left);
  521. const spawnWorldY = lineNode.worldPosition.y;
  522. // 根据生成位置计算漂移目标位置
  523. let driftWorldX = spawnWorldX;
  524. let driftWorldY = spawnWorldY;
  525. // 获取屏幕边界(Canvas边界)
  526. const canvas = find('Canvas');
  527. if (canvas) {
  528. const canvasUI = canvas.getComponent(UITransform);
  529. if (canvasUI) {
  530. const screenHeight = canvasUI.height;
  531. const canvasWorldPos = canvas.worldPosition;
  532. if (fromTop) {
  533. // 从Line1生成,漂移到屏幕上边界位置-30px
  534. const screenTop = canvasWorldPos.y + screenHeight / 2;
  535. driftWorldY = screenTop - 30;
  536. } else {
  537. // 从Line2生成,漂移到屏幕下边界位置+30px
  538. const screenBottom = canvasWorldPos.y - screenHeight / 2;
  539. driftWorldY = screenBottom + 30;
  540. }
  541. }
  542. }
  543. // 设置初始位置(线上的位置)
  544. const initialWorldPos = new Vec3(spawnWorldX, spawnWorldY, 0);
  545. const initialLocalPos = enemyContainer.getComponent(UITransform).convertToNodeSpaceAR(initialWorldPos);
  546. enemy.position = initialLocalPos;
  547. // 记录漂移目标位置(墙体附近的位置)
  548. const driftWorldPos = new Vec3(driftWorldX, driftWorldY, 0);
  549. // === 根据配置设置敌人 ===
  550. const enemyComp = enemy.addComponent(EnemyInstance);
  551. // 确保敌人数据库已加载
  552. await EnemyInstance.loadEnemyDatabase();
  553. let enemyConfig: EnemyConfig = null;
  554. let enemyId: string = null;
  555. if (this.configManager && this.configManager.isConfigLoaded()) {
  556. // 优先使用当前波次配置中的敌人类型
  557. if (this.currentWaveEnemyConfigs.length > 0) {
  558. const configIndex = this.currentWaveEnemiesSpawned % this.currentWaveEnemyConfigs.length;
  559. const enemyTypeConfig = this.currentWaveEnemyConfigs[configIndex];
  560. const enemyType = enemyTypeConfig.enemyType || enemyTypeConfig;
  561. // enemyType本身就是敌人ID,直接使用
  562. enemyId = enemyType;
  563. console.log(`[EnemyController] 使用敌人类型: ${enemyType} 作为敌人ID`);
  564. enemyConfig = this.configManager.getEnemyById(enemyId) || this.configManager.getRandomEnemy();
  565. } else {
  566. enemyConfig = this.configManager.getRandomEnemy();
  567. enemyId = enemyConfig?.id || 'normal_zombie';
  568. }
  569. }
  570. // 获取当前关卡的血量倍率
  571. const healthMultiplier = await this.getCurrentHealthMultiplier();
  572. if (enemyConfig && enemyId) {
  573. try {
  574. const cfgComp = enemy.addComponent(EnemyComponent);
  575. cfgComp.enemyConfig = enemyConfig;
  576. cfgComp.spawner = this;
  577. } catch (error) {
  578. console.error(`[EnemyController] 添加EnemyComponent失败:`, error);
  579. }
  580. // 使用EnemyInstance的新配置系统
  581. try {
  582. // 设置敌人配置
  583. enemyComp.setEnemyConfig(enemyId);
  584. // 应用血量倍率
  585. const baseHealth = enemyComp.health || this.defaultHealth;
  586. const finalHealth = Math.round(baseHealth * healthMultiplier);
  587. enemyComp.health = finalHealth;
  588. enemyComp.maxHealth = finalHealth;
  589. console.log(`[EnemyController] 敌人 ${enemyId} 配置已应用,血量: ${finalHealth}`);
  590. } catch (error) {
  591. console.error(`[EnemyController] 应用敌人配置时出错:`, error);
  592. // 使用默认值
  593. const finalHealth = Math.round(this.defaultHealth * healthMultiplier);
  594. enemyComp.health = finalHealth;
  595. enemyComp.maxHealth = finalHealth;
  596. enemyComp.speed = this.defaultEnemySpeed;
  597. enemyComp.attackPower = this.defaultAttackPower;
  598. }
  599. // 加载动画
  600. this.loadEnemyAnimation(enemy, enemyConfig);
  601. } else {
  602. // 使用默认配置
  603. try {
  604. enemyComp.setEnemyConfig('normal_zombie'); // 默认敌人类型
  605. const baseHealth = enemyComp.health || this.defaultHealth;
  606. const finalHealth = Math.round(baseHealth * healthMultiplier);
  607. enemyComp.health = finalHealth;
  608. enemyComp.maxHealth = finalHealth;
  609. } catch (error) {
  610. console.error(`[EnemyController] 应用默认敌人配置时出错:`, error);
  611. // 使用硬编码默认值
  612. const finalHealth = Math.round(this.defaultHealth * healthMultiplier);
  613. enemyComp.health = finalHealth;
  614. enemyComp.maxHealth = finalHealth;
  615. enemyComp.speed = this.defaultEnemySpeed;
  616. enemyComp.attackPower = this.defaultAttackPower;
  617. }
  618. }
  619. // 额外的属性设置
  620. enemyComp.spawnFromTop = fromTop;
  621. enemyComp.targetFence = fromTop ?
  622. find('Canvas/GameLevelUI/GameArea/TopFence') :
  623. find('Canvas/GameLevelUI/GameArea/BottomFence');
  624. // 设置漂移目标位置(墙体附近的位置)
  625. enemyComp.driftTargetPosition = driftWorldPos.clone();
  626. // 计算墙体上的随机目标位置
  627. if (enemyComp.targetFence && enemyComp.targetFence.isValid) {
  628. const fenceWorldPos = enemyComp.targetFence.worldPosition.clone();
  629. const fenceTransform = enemyComp.targetFence.getComponent(UITransform);
  630. if (fenceTransform) {
  631. // 在墙体宽度范围内随机选择X坐标
  632. const fenceWidth = fenceTransform.width;
  633. const randomX = fenceWorldPos.x + (Math.random() - 0.5) * fenceWidth * 0.8; // 0.8是为了避免太靠近边缘
  634. enemyComp.targetPosition = new Vec3(randomX, fenceWorldPos.y, fenceWorldPos.z);
  635. } else {
  636. // 如果无法获取墙体尺寸,使用墙体中心位置
  637. enemyComp.targetPosition = fenceWorldPos;
  638. }
  639. }
  640. enemyComp.movingDirection = Math.random() > 0.5 ? 1 : -1;
  641. enemyComp.targetY = fromTop ?
  642. this.gameBounds.top - 50 :
  643. this.gameBounds.bottom + 50;
  644. enemyComp.changeDirectionTime = 0;
  645. enemyComp.controller = this;
  646. // 更新敌人血量显示
  647. enemyComp.updateHealthDisplay();
  648. // 添加到活跃敌人列表
  649. this.activeEnemies.push(enemy);
  650. // 增加已生成敌人计数
  651. this.currentWaveEnemiesSpawned++;
  652. // 生成敌人时不更新敌人数量显示,避免重置计数
  653. }
  654. // 清除所有敌人
  655. clearAllEnemies(triggerEvents: boolean = true) {
  656. // 设置清理标志,阻止清理过程中触发游戏胜利判断
  657. if (!triggerEvents) {
  658. this.isClearing = true;
  659. }
  660. // 如果不触发事件,先暂时禁用 notifyEnemyDead 方法
  661. const originalNotifyMethod = this.notifyEnemyDead;
  662. if (!triggerEvents) {
  663. // 临时替换为空函数
  664. this.notifyEnemyDead = () => {};
  665. }
  666. for (const enemy of this.activeEnemies) {
  667. if (enemy && enemy.isValid) {
  668. enemy.destroy();
  669. }
  670. }
  671. // 恢复原来的方法
  672. if (!triggerEvents) {
  673. this.notifyEnemyDead = originalNotifyMethod;
  674. }
  675. this.activeEnemies = [];
  676. // 重置清理标志
  677. if (!triggerEvents) {
  678. this.isClearing = false;
  679. }
  680. // 清除敌人时不更新敌人数量显示,避免重置计数
  681. }
  682. // 获取所有活跃的敌人
  683. getActiveEnemies(): Node[] {
  684. // 过滤掉已经无效的敌人
  685. this.activeEnemies = this.activeEnemies.filter(enemy => enemy && enemy.isValid);
  686. return this.activeEnemies;
  687. }
  688. // 获取当前敌人数量
  689. getCurrentEnemyCount(): number {
  690. return this.getActiveEnemies().length;
  691. }
  692. // 获取最近的敌人节点(排除漂移状态的敌人)
  693. public getNearestEnemy(fromPosition: Vec3): Node | null {
  694. const enemies = this.getActiveEnemies();
  695. if (enemies.length === 0) return null;
  696. // 过滤掉漂移状态的敌人
  697. const nonDriftingEnemies = enemies.filter(enemy => {
  698. const enemyInstance = enemy.getComponent('EnemyInstance') as any;
  699. return !enemyInstance || !enemyInstance.isDrifting();
  700. });
  701. if (nonDriftingEnemies.length === 0) return null;
  702. let nearestEnemy: Node = null;
  703. let nearestDistance = Infinity;
  704. for (const enemy of nonDriftingEnemies) {
  705. const distance = Vec3.distance(fromPosition, enemy.worldPosition);
  706. if (distance < nearestDistance) {
  707. nearestDistance = distance;
  708. nearestEnemy = enemy;
  709. }
  710. }
  711. return nearestEnemy;
  712. }
  713. // 检查是否有活跃敌人(排除漂移状态的敌人)
  714. public hasActiveEnemies(): boolean {
  715. const activeEnemies = this.getActiveEnemies();
  716. // 过滤掉漂移状态的敌人
  717. const nonDriftingEnemies = activeEnemies.filter(enemy => {
  718. const enemyInstance = enemy.getComponent('EnemyInstance') as any;
  719. return !enemyInstance || !enemyInstance.isDrifting();
  720. });
  721. return nonDriftingEnemies.length > 0;
  722. }
  723. // 调试方法:检查enemyContainer中的实际敌人节点
  724. private debugEnemyContainer() {
  725. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  726. if (!enemyContainer) {
  727. return;
  728. }
  729. let enemyNodeCount = 0;
  730. enemyContainer.children.forEach((child, index) => {
  731. if (child.name === 'Enemy' || child.name.includes('Enemy')) {
  732. enemyNodeCount++;
  733. }
  734. });
  735. }
  736. // 调试方法:强制清理无效敌人引用
  737. public debugCleanupEnemies() {
  738. const beforeCount = this.activeEnemies.length;
  739. this.activeEnemies = this.activeEnemies.filter(enemy => enemy && enemy.isValid);
  740. const afterCount = this.activeEnemies.length;
  741. return afterCount;
  742. }
  743. // 获取游戏是否已开始状态
  744. public isGameStarted(): boolean {
  745. return this.gameStarted;
  746. }
  747. // 暂停生成敌人
  748. public pauseSpawning(): void {
  749. if (this.gameStarted) {
  750. this.unschedule(this.spawnEnemy);
  751. // 触发敌人生成停止事件
  752. const eventBus = EventBus.getInstance();
  753. eventBus.emit(GameEvents.ENEMY_SPAWNING_STOPPED);
  754. }
  755. }
  756. // 恢复生成敌人
  757. public resumeSpawning(): void {
  758. // 游戏状态检查现在通过事件系统处理
  759. if (!this.gameStarted) {
  760. return;
  761. }
  762. // 检查是否已达到当前波次的敌人生成上限
  763. if (this.currentWaveEnemiesSpawned >= this.currentWaveTotalEnemies) {
  764. return;
  765. }
  766. // 确保先取消之前的定时器,避免重复调度
  767. this.unschedule(this.spawnEnemy);
  768. this.schedule(this.spawnEnemy, this.spawnInterval);
  769. // 触发敌人生成开始事件
  770. const eventBus = EventBus.getInstance();
  771. eventBus.emit(GameEvents.ENEMY_SPAWNING_STARTED);
  772. }
  773. // 敌人受到伤害
  774. damageEnemy(enemy: Node, damage: number, isCritical: boolean = false) {
  775. if (!enemy || !enemy.isValid) return;
  776. // 游戏状态检查现在通过事件系统处理
  777. // 获取敌人组件
  778. const enemyComp = enemy.getComponent(EnemyInstance);
  779. if (!enemyComp) return;
  780. // 减少敌人血量
  781. enemyComp.takeDamage(damage, isCritical);
  782. // 检查敌人是否死亡
  783. if (enemyComp.health <= 0) {
  784. // 从活跃敌人列表中移除
  785. const index = this.activeEnemies.indexOf(enemy);
  786. if (index !== -1) {
  787. this.activeEnemies.splice(index, 1);
  788. }
  789. // 清理敌人身上的所有灼烧效果,防止定时器继续运行
  790. try {
  791. const burnEffect = enemy.getComponent(BurnEffect);
  792. if (burnEffect) {
  793. console.log(`[EnemyController] 清理敌人身上的灼烧效果`);
  794. // 先停止灼烧效果,再移除组件
  795. burnEffect.stopBurnEffect();
  796. enemy.removeComponent(BurnEffect);
  797. }
  798. } catch (error) {
  799. console.warn(`[EnemyController] 清理灼烧效果时出错:`, error);
  800. }
  801. // 敌人死亡时不在这里更新数量显示,由GameManager统一管理
  802. // 延迟销毁敌人,避免在物理碰撞监听器中直接销毁导致的刚体激活错误
  803. this.scheduleOnce(() => {
  804. if (enemy && enemy.isValid) {
  805. enemy.destroy();
  806. }
  807. }, 0);
  808. }
  809. }
  810. // 墙体受到伤害 - 现在委托给Wall组件
  811. damageWall(damage: number) {
  812. if (this.wallComponent) {
  813. this.wallComponent.takeDamage(damage);
  814. } else {
  815. console.warn('[EnemyController] 墙体组件未找到,无法处理伤害');
  816. }
  817. }
  818. // 游戏结束
  819. gameOver() {
  820. // 停止游戏,但不清除敌人
  821. this.stopGame(false);
  822. // 通过事件系统触发游戏失败
  823. const eventBus = EventBus.getInstance();
  824. eventBus.emit(GameEvents.GAME_DEFEAT);
  825. }
  826. update(dt: number) {
  827. if (!this.gameStarted) return;
  828. // 更新所有敌人
  829. for (let i = this.activeEnemies.length - 1; i >= 0; i--) {
  830. const enemy = this.activeEnemies[i];
  831. if (!enemy || !enemy.isValid) {
  832. this.activeEnemies.splice(i, 1);
  833. continue;
  834. }
  835. // 敌人更新由各自的组件处理
  836. // 不再需要检查敌人是否到达墙体,因为敌人到达游戏区域后会自动攻击
  837. // 敌人的攻击逻辑已经在EnemyInstance中处理
  838. }
  839. }
  840. public getCurrentWallHealth(): number {
  841. return this.wallComponent ? this.wallComponent.getCurrentHealth() : 0;
  842. }
  843. public forceEnemyAttack() {
  844. const activeEnemies = this.getActiveEnemies();
  845. for (const enemy of activeEnemies) {
  846. const enemyComp = enemy.getComponent(EnemyInstance);
  847. if (enemyComp) {
  848. // 直接调用damageWall方法进行测试
  849. this.damageWall(enemyComp.attackPower);
  850. }
  851. }
  852. }
  853. /** 供 EnemyInstance 在 onDestroy 中调用 */
  854. public notifyEnemyDead(enemyNode?: Node) {
  855. // 如果正在清理敌人,不触发任何游戏事件
  856. if (this.isClearing) {
  857. if (enemyNode) {
  858. const idx = this.activeEnemies.indexOf(enemyNode);
  859. if (idx !== -1) {
  860. this.activeEnemies.splice(idx, 1);
  861. }
  862. }
  863. return;
  864. }
  865. if (enemyNode) {
  866. const idx = this.activeEnemies.indexOf(enemyNode);
  867. if (idx !== -1) {
  868. this.activeEnemies.splice(idx, 1);
  869. } else {
  870. console.log(`[EnemyController] 警告:尝试移除的敌人不在activeEnemies数组中!`);
  871. }
  872. // 移除EnemyController内部的击杀计数,统一由GameManager管理
  873. // this.currentWaveEnemiesKilled++;
  874. // 敌人死亡通知时不更新数量显示,由GameManager统一管理
  875. }
  876. // 直接通过事件总线发送ENEMY_KILLED事件,避免通过GamePause的双重调用
  877. const eventBus = EventBus.getInstance();
  878. eventBus.emit('ENEMY_KILLED');
  879. }
  880. /**
  881. * 加载敌人骨骼动画
  882. */
  883. private loadEnemyAnimation(enemyNode: Node, enemyConfig: EnemyConfig) {
  884. console.log(`[EnemyController] 开始加载敌人动画,敌人ID: ${enemyConfig?.id}, 敌人名称: ${enemyConfig?.name}`);
  885. if (!enemyConfig || !enemyConfig.visualConfig) {
  886. console.warn('[EnemyController] 敌人配置或视觉配置缺失,使用默认动画');
  887. return;
  888. }
  889. let spinePath: string | undefined = enemyConfig.visualConfig?.spritePath;
  890. console.log(`[EnemyController] 敌人 ${enemyConfig.id} 的spritePath: ${spinePath}`);
  891. if (!spinePath) {
  892. console.warn('[EnemyController] 敌人精灵路径缺失');
  893. return;
  894. }
  895. if (spinePath.startsWith('@EnemyAni')) {
  896. spinePath = spinePath.replace('@EnemyAni', 'Animation/EnemyAni');
  897. }
  898. if (spinePath.startsWith('@')) {
  899. spinePath = spinePath.substring(1);
  900. }
  901. // 对于Animation/EnemyAni路径,需要添加子目录和文件名
  902. // 例如:Animation/EnemyAni/007 -> Animation/EnemyAni/007/007
  903. if (spinePath.startsWith('Animation/EnemyAni/')) {
  904. const parts = spinePath.split('/');
  905. if (parts.length === 3) {
  906. const animId = parts[2];
  907. spinePath = `${spinePath}/${animId}`;
  908. }
  909. }
  910. console.log(`[EnemyController] 最终加载路径: ${spinePath}`);
  911. resources.load(spinePath, sp.SkeletonData, (err, skeletonData) => {
  912. if (err) {
  913. console.warn(`加载敌人Spine动画失败: ${spinePath}`, err);
  914. return;
  915. }
  916. // 获取EnemySprite子节点
  917. const enemySprite = enemyNode.getChildByName('EnemySprite');
  918. if (!enemySprite) {
  919. console.error('[EnemyController] 未找到EnemySprite子节点,无法设置骨骼动画');
  920. return;
  921. }
  922. let skeleton = enemySprite.getComponent(sp.Skeleton);
  923. if (!skeleton) {
  924. skeleton = enemySprite.addComponent(sp.Skeleton);
  925. }
  926. skeleton.skeletonData = skeletonData;
  927. const anims = enemyConfig.visualConfig.animations;
  928. const walkName = anims?.walk ?? 'walk';
  929. const idleName = anims?.idle ?? 'idle';
  930. if (skeleton.findAnimation(walkName)) {
  931. skeleton.setAnimation(0, walkName, true);
  932. } else if (skeleton.findAnimation(idleName)) {
  933. skeleton.setAnimation(0, idleName, true);
  934. } else {
  935. console.warn(`[EnemyController] 未找到合适的动画,walk: ${walkName}, idle: ${idleName}`);
  936. }
  937. });
  938. }
  939. // 更新敌人数量显示
  940. public updateEnemyCountLabel(killedCount?: number) {
  941. if (!this.enemyCountLabelNode) {
  942. console.warn('[EnemyController] enemyCountLabelNode 未找到,无法更新敌人数量显示');
  943. return;
  944. }
  945. const label = this.enemyCountLabelNode.getComponent(Label);
  946. if (label) {
  947. // 计算剩余敌人数量:总数 - 击杀数量
  948. let remaining: number;
  949. if (killedCount !== undefined) {
  950. // 使用传入的击杀数量计算剩余数量
  951. remaining = Math.max(0, this.currentWaveTotalEnemies - killedCount);
  952. } else {
  953. // 如果没有传入击杀数量,则显示当前波次总敌人数(初始状态)
  954. remaining = this.currentWaveTotalEnemies;
  955. }
  956. label.string = remaining.toString();
  957. } else {
  958. console.warn('[EnemyController] enemyCountLabelNode 上未找到 Label 组件');
  959. }
  960. }
  961. public startWave(waveNum: number, totalWaves: number, totalEnemies: number, waveEnemyConfigs?: any[]) {
  962. this.currentWave = waveNum;
  963. this.totalWaves = totalWaves;
  964. this.currentWaveTotalEnemies = totalEnemies;
  965. this.currentWaveEnemiesSpawned = 0; // 重置已生成敌人计数器
  966. this.currentWaveEnemyConfigs = waveEnemyConfigs || []; // 存储当前波次的敌人配置
  967. // 移除EnemyController内部的击杀计数重置,统一由GameManager管理
  968. // this.currentWaveEnemiesKilled = 0;
  969. // 修复问题1:根据波次配置设置生成间隔
  970. if (this.currentWaveEnemyConfigs.length > 0) {
  971. // 使用第一个敌人配置的spawnInterval,如果有多个配置可以取平均值或最小值
  972. const firstEnemyConfig = this.currentWaveEnemyConfigs[0];
  973. if (firstEnemyConfig && typeof firstEnemyConfig.spawnInterval === 'number') {
  974. this.spawnInterval = firstEnemyConfig.spawnInterval;
  975. console.log(`[EnemyController] 设置生成间隔为: ${this.spawnInterval}`);
  976. }
  977. }
  978. console.log(`[EnemyController] 开始波次 ${waveNum}/${totalWaves},需要生成 ${totalEnemies} 个敌人`);
  979. console.log(`[EnemyController] 波次敌人配置:`, this.currentWaveEnemyConfigs);
  980. console.log(`[EnemyController] 当前生成间隔: ${this.spawnInterval}`);
  981. this.updateWaveLabel();
  982. this.updateEnemyCountLabel();
  983. // 移除startWaveUI的隐藏,因为现在使用Toast预制体
  984. // if (this.startWaveUI) this.startWaveUI.active = false;
  985. }
  986. private updateWaveLabel() {
  987. // 更新当前波数显示
  988. if (this.currentWaveNumberLabelNode) {
  989. const currentLabel = this.currentWaveNumberLabelNode.getComponent(Label);
  990. if (currentLabel) {
  991. currentLabel.string = this.currentWave.toString();
  992. } else {
  993. console.warn('[EnemyController] currentWaveNumberLabelNode 上未找到 Label 组件');
  994. }
  995. } else {
  996. console.warn('[EnemyController] currentWaveNumberLabelNode 未找到,无法更新当前波次标签');
  997. }
  998. // 更新总波数显示
  999. if (this.totalWaveNumberLabelNode) {
  1000. const totalLabel = this.totalWaveNumberLabelNode.getComponent(Label);
  1001. if (totalLabel) {
  1002. totalLabel.string = this.totalWaves.toString();
  1003. } else {
  1004. console.warn('[EnemyController] totalWaveNumberLabelNode 上未找到 Label 组件');
  1005. }
  1006. } else {
  1007. console.warn('[EnemyController] totalWaveNumberLabelNode 未找到,无法更新总波次标签');
  1008. }
  1009. }
  1010. /** 显示每波开始提示,随后开启敌人生成 */
  1011. public showStartWavePromptUI(duration: number = 2) {
  1012. // 通过事件系统检查游戏是否已经结束
  1013. let gameOver = false;
  1014. EventBus.getInstance().emit(GameEvents.GAME_CHECK_OVER, (isOver: boolean) => {
  1015. gameOver = isOver;
  1016. });
  1017. if (gameOver) {
  1018. return;
  1019. }
  1020. // 暂停敌人生成,确保在Toast显示期间不会生成敌人
  1021. this.pauseSpawning();
  1022. // 使用事件机制显示Toast
  1023. const toastText = `第${this.currentWave}波敌人来袭!`;
  1024. EventBus.getInstance().emit(GameEvents.SHOW_TOAST, {
  1025. message: toastText,
  1026. duration: duration
  1027. });
  1028. // 等待Toast消息播放结束后再开始生成敌人
  1029. if (duration > 0) {
  1030. this.scheduleOnce(() => {
  1031. // 再次检查游戏状态,确保游戏未结束
  1032. let gameOverCheck = false;
  1033. EventBus.getInstance().emit(GameEvents.GAME_CHECK_OVER, (isOver: boolean) => {
  1034. gameOverCheck = isOver;
  1035. });
  1036. if (gameOverCheck) {
  1037. return;
  1038. }
  1039. // Toast播放完毕,开始生成敌人
  1040. this.startGame();
  1041. }, duration);
  1042. } else {
  1043. // 如果duration为0,立即开始游戏
  1044. this.startGame();
  1045. }
  1046. }
  1047. /**
  1048. * 重置到初始状态
  1049. * 用于游戏重新开始时重置所有敌人相关状态
  1050. */
  1051. public resetToInitialState(): void {
  1052. // 停止游戏并清理所有敌人
  1053. this.stopGame(true);
  1054. // 重置波次信息
  1055. this.currentWave = 1;
  1056. this.totalWaves = 1;
  1057. this.currentWaveTotalEnemies = 0;
  1058. this.currentWaveEnemiesKilled = 0;
  1059. this.currentWaveEnemiesSpawned = 0;
  1060. this.currentWaveEnemyConfigs = [];
  1061. // 重置血量倍率
  1062. this.currentHealthMultiplier = 1.0;
  1063. // 清空暂停状态
  1064. this.pausedEnemyStates.clear();
  1065. // 重置UI显示
  1066. this.updateEnemyCountLabel();
  1067. this.updateWaveLabel();
  1068. }
  1069. /**
  1070. * 处理更新敌人计数事件
  1071. */
  1072. private onUpdateEnemyCountEvent(killedCount: number) {
  1073. this.updateEnemyCountLabel(killedCount);
  1074. }
  1075. /**
  1076. * 处理启动波次事件
  1077. */
  1078. private onStartWaveEvent(data: { wave: number; totalWaves: number; enemyCount: number; waveEnemyConfigs: any[] }) {
  1079. this.startWave(data.wave, data.totalWaves, data.enemyCount, data.waveEnemyConfigs);
  1080. }
  1081. /**
  1082. * 处理启动游戏事件
  1083. */
  1084. private onStartGameEvent() {
  1085. this.startGame();
  1086. }
  1087. /**
  1088. * 处理显示波次提示事件
  1089. */
  1090. private onShowStartWavePromptEvent() {
  1091. this.showStartWavePromptUI();
  1092. }
  1093. onDestroy() {
  1094. // 清理事件监听
  1095. const eventBus = EventBus.getInstance();
  1096. eventBus.off(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
  1097. eventBus.off(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  1098. eventBus.off(GameEvents.GAME_SUCCESS, this.onGameEndEvent, this);
  1099. eventBus.off(GameEvents.GAME_DEFEAT, this.onGameEndEvent, this);
  1100. eventBus.off(GameEvents.CLEAR_ALL_GAME_OBJECTS, this.onClearAllGameObjectsEvent, this);
  1101. eventBus.off(GameEvents.CLEAR_ALL_ENEMIES, this.onClearAllEnemiesEvent, this);
  1102. eventBus.off(GameEvents.RESET_ENEMY_CONTROLLER, this.onResetEnemyControllerEvent, this);
  1103. // 清理新增的事件监听
  1104. eventBus.off(GameEvents.ENEMY_UPDATE_COUNT, this.onUpdateEnemyCountEvent, this);
  1105. eventBus.off(GameEvents.ENEMY_START_WAVE, this.onStartWaveEvent, this);
  1106. eventBus.off(GameEvents.ENEMY_START_GAME, this.onStartGameEvent, this);
  1107. eventBus.off(GameEvents.ENEMY_SHOW_START_WAVE_PROMPT, this.onShowStartWavePromptEvent, this);
  1108. // 清空状态
  1109. this.pausedEnemyStates.clear();
  1110. }
  1111. }