EnemyController.ts 43 KB

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