EnemyController.ts 50 KB

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