EnemyController.ts 42 KB

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