EnemyController.ts 51 KB

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