EnemyController.ts 49 KB

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