EnemyController.ts 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  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. // 游戏结束
  426. stopGame(clearEnemies: boolean = true) {
  427. this.gameStarted = false;
  428. // 停止生成敌人
  429. this.unschedule(this.spawnEnemy);
  430. // 只有在指定时才清除所有敌人
  431. if (clearEnemies) {
  432. // 清除敌人,在重置状态时不触发事件,避免错误的游戏成功判定
  433. this.clearAllEnemies(false);
  434. }
  435. }
  436. // 生成敌人
  437. async spawnEnemy() {
  438. if (!this.gameStarted || !this.enemyPrefab) {
  439. return;
  440. }
  441. // 游戏状态检查现在通过事件系统处理
  442. // 检查是否已达到当前波次的敌人生成上限
  443. if (this.currentWaveEnemiesSpawned >= this.currentWaveTotalEnemies) {
  444. this.unschedule(this.spawnEnemy); // 停止定时生成
  445. return;
  446. }
  447. // 随机决定从上方还是下方生成
  448. const fromTop = Math.random() > 0.5;
  449. // 实例化敌人
  450. const enemy = instantiate(this.enemyPrefab) as Node;
  451. enemy.name = 'Enemy'; // 确保敌人节点名称为Enemy
  452. // 添加到场景中
  453. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  454. if (!enemyContainer) {
  455. return;
  456. }
  457. enemyContainer.addChild(enemy);
  458. // 生成在对应线(Line1 / Line2)上的随机位置
  459. const lineName = fromTop ? 'Line1' : 'Line2';
  460. const lineNode = enemyContainer.getChildByName(lineName);
  461. if (!lineNode) {
  462. console.warn(`[EnemyController] 未找到 ${lineName} 节点,取消本次敌人生成`);
  463. enemy.destroy();
  464. return;
  465. }
  466. // 在对应 line 上随机 X 坐标
  467. const spawnWorldX = this.gameBounds.left + Math.random() * (this.gameBounds.right - this.gameBounds.left);
  468. const spawnWorldY = lineNode.worldPosition.y;
  469. const worldPos = new Vec3(spawnWorldX, spawnWorldY, 0);
  470. const localPos = enemyContainer.getComponent(UITransform).convertToNodeSpaceAR(worldPos);
  471. enemy.position = localPos;
  472. // === 根据配置设置敌人 ===
  473. const enemyComp = enemy.addComponent(EnemyInstance);
  474. // 确保敌人数据库已加载
  475. await EnemyInstance.loadEnemyDatabase();
  476. let enemyConfig: EnemyConfig = null;
  477. let enemyId: string = null;
  478. if (this.configManager && this.configManager.isConfigLoaded()) {
  479. // 优先使用当前波次配置中的敌人类型
  480. if (this.currentWaveEnemyConfigs.length > 0) {
  481. const configIndex = this.currentWaveEnemiesSpawned % this.currentWaveEnemyConfigs.length;
  482. const enemyTypeConfig = this.currentWaveEnemyConfigs[configIndex];
  483. const enemyType = enemyTypeConfig.enemyType || enemyTypeConfig;
  484. // enemyType本身就是敌人ID,直接使用
  485. enemyId = enemyType;
  486. console.log(`[EnemyController] 使用敌人类型: ${enemyType} 作为敌人ID`);
  487. enemyConfig = this.configManager.getEnemyById(enemyId) || this.configManager.getRandomEnemy();
  488. } else {
  489. enemyConfig = this.configManager.getRandomEnemy();
  490. enemyId = enemyConfig?.id || 'normal_zombie';
  491. }
  492. }
  493. // 获取当前关卡的血量倍率
  494. const healthMultiplier = await this.getCurrentHealthMultiplier();
  495. if (enemyConfig && enemyId) {
  496. try {
  497. const cfgComp = enemy.addComponent(EnemyComponent);
  498. cfgComp.enemyConfig = enemyConfig;
  499. cfgComp.spawner = this;
  500. } catch (error) {
  501. console.error(`[EnemyController] 添加EnemyComponent失败:`, error);
  502. }
  503. // 使用EnemyInstance的新配置系统
  504. try {
  505. // 设置敌人配置
  506. enemyComp.setEnemyConfig(enemyId);
  507. // 应用血量倍率
  508. const baseHealth = enemyComp.health || this.defaultHealth;
  509. const finalHealth = Math.round(baseHealth * healthMultiplier);
  510. enemyComp.health = finalHealth;
  511. enemyComp.maxHealth = finalHealth;
  512. console.log(`[EnemyController] 敌人 ${enemyId} 配置已应用,血量: ${finalHealth}`);
  513. } catch (error) {
  514. console.error(`[EnemyController] 应用敌人配置时出错:`, error);
  515. // 使用默认值
  516. const finalHealth = Math.round(this.defaultHealth * healthMultiplier);
  517. enemyComp.health = finalHealth;
  518. enemyComp.maxHealth = finalHealth;
  519. enemyComp.speed = this.defaultEnemySpeed;
  520. enemyComp.attackPower = this.defaultAttackPower;
  521. }
  522. // 加载动画
  523. this.loadEnemyAnimation(enemy, enemyConfig);
  524. } else {
  525. // 使用默认配置
  526. try {
  527. enemyComp.setEnemyConfig('normal_zombie'); // 默认敌人类型
  528. const baseHealth = enemyComp.health || this.defaultHealth;
  529. const finalHealth = Math.round(baseHealth * healthMultiplier);
  530. enemyComp.health = finalHealth;
  531. enemyComp.maxHealth = finalHealth;
  532. } catch (error) {
  533. console.error(`[EnemyController] 应用默认敌人配置时出错:`, error);
  534. // 使用硬编码默认值
  535. const finalHealth = Math.round(this.defaultHealth * healthMultiplier);
  536. enemyComp.health = finalHealth;
  537. enemyComp.maxHealth = finalHealth;
  538. enemyComp.speed = this.defaultEnemySpeed;
  539. enemyComp.attackPower = this.defaultAttackPower;
  540. }
  541. }
  542. // 额外的属性设置
  543. enemyComp.spawnFromTop = fromTop;
  544. enemyComp.targetFence = find(fromTop ? 'Canvas/GameLevelUI/GameArea/TopFence' : 'Canvas/GameLevelUI/GameArea/BottomFence');
  545. enemyComp.movingDirection = Math.random() > 0.5 ? 1 : -1;
  546. enemyComp.targetY = fromTop ? this.gameBounds.top - 50 : this.gameBounds.bottom + 50;
  547. enemyComp.changeDirectionTime = 0;
  548. enemyComp.controller = this;
  549. // 更新敌人血量显示
  550. enemyComp.updateHealthDisplay();
  551. // 添加到活跃敌人列表
  552. this.activeEnemies.push(enemy);
  553. // 增加已生成敌人计数
  554. this.currentWaveEnemiesSpawned++;
  555. // 生成敌人时不更新敌人数量显示,避免重置计数
  556. }
  557. // 清除所有敌人
  558. clearAllEnemies(triggerEvents: boolean = true) {
  559. // 设置清理标志,阻止清理过程中触发游戏胜利判断
  560. if (!triggerEvents) {
  561. this.isClearing = true;
  562. }
  563. // 如果不触发事件,先暂时禁用 notifyEnemyDead 方法
  564. const originalNotifyMethod = this.notifyEnemyDead;
  565. if (!triggerEvents) {
  566. // 临时替换为空函数
  567. this.notifyEnemyDead = () => {};
  568. }
  569. for (const enemy of this.activeEnemies) {
  570. if (enemy && enemy.isValid) {
  571. enemy.destroy();
  572. }
  573. }
  574. // 恢复原来的方法
  575. if (!triggerEvents) {
  576. this.notifyEnemyDead = originalNotifyMethod;
  577. }
  578. this.activeEnemies = [];
  579. // 重置清理标志
  580. if (!triggerEvents) {
  581. this.isClearing = false;
  582. }
  583. // 清除敌人时不更新敌人数量显示,避免重置计数
  584. }
  585. // 获取所有活跃的敌人
  586. getActiveEnemies(): Node[] {
  587. // 过滤掉已经无效的敌人
  588. this.activeEnemies = this.activeEnemies.filter(enemy => enemy && enemy.isValid);
  589. return this.activeEnemies;
  590. }
  591. // 获取当前敌人数量
  592. getCurrentEnemyCount(): number {
  593. return this.getActiveEnemies().length;
  594. }
  595. // 获取最近的敌人节点
  596. public getNearestEnemy(fromPosition: Vec3): Node | null {
  597. const enemies = this.getActiveEnemies();
  598. if (enemies.length === 0) return null;
  599. let nearestEnemy: Node = null;
  600. let nearestDistance = Infinity;
  601. for (const enemy of enemies) {
  602. const distance = Vec3.distance(fromPosition, enemy.worldPosition);
  603. if (distance < nearestDistance) {
  604. nearestDistance = distance;
  605. nearestEnemy = enemy;
  606. }
  607. }
  608. return nearestEnemy;
  609. }
  610. // 检查是否有活跃敌人
  611. public hasActiveEnemies(): boolean {
  612. const activeCount = this.getActiveEnemies().length;
  613. return activeCount > 0;
  614. }
  615. // 调试方法:检查enemyContainer中的实际敌人节点
  616. private debugEnemyContainer() {
  617. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  618. if (!enemyContainer) {
  619. return;
  620. }
  621. let enemyNodeCount = 0;
  622. enemyContainer.children.forEach((child, index) => {
  623. if (child.name === 'Enemy' || child.name.includes('Enemy')) {
  624. enemyNodeCount++;
  625. }
  626. });
  627. }
  628. // 调试方法:强制清理无效敌人引用
  629. public debugCleanupEnemies() {
  630. const beforeCount = this.activeEnemies.length;
  631. this.activeEnemies = this.activeEnemies.filter(enemy => enemy && enemy.isValid);
  632. const afterCount = this.activeEnemies.length;
  633. return afterCount;
  634. }
  635. // 获取游戏是否已开始状态
  636. public isGameStarted(): boolean {
  637. return this.gameStarted;
  638. }
  639. // 暂停生成敌人
  640. public pauseSpawning(): void {
  641. if (this.gameStarted) {
  642. this.unschedule(this.spawnEnemy);
  643. }
  644. }
  645. // 恢复生成敌人
  646. public resumeSpawning(): void {
  647. // 游戏状态检查现在通过事件系统处理
  648. if (!this.gameStarted) {
  649. return;
  650. }
  651. // 检查是否已达到当前波次的敌人生成上限
  652. if (this.currentWaveEnemiesSpawned >= this.currentWaveTotalEnemies) {
  653. return;
  654. }
  655. // 确保先取消之前的定时器,避免重复调度
  656. this.unschedule(this.spawnEnemy);
  657. this.schedule(this.spawnEnemy, this.spawnInterval);
  658. }
  659. // 敌人受到伤害
  660. damageEnemy(enemy: Node, damage: number, isCritical: boolean = false) {
  661. if (!enemy || !enemy.isValid) return;
  662. // 游戏状态检查现在通过事件系统处理
  663. // 获取敌人组件
  664. const enemyComp = enemy.getComponent(EnemyInstance);
  665. if (!enemyComp) return;
  666. // 减少敌人血量
  667. enemyComp.takeDamage(damage, isCritical);
  668. // 检查敌人是否死亡
  669. if (enemyComp.health <= 0) {
  670. // 从活跃敌人列表中移除
  671. const index = this.activeEnemies.indexOf(enemy);
  672. if (index !== -1) {
  673. this.activeEnemies.splice(index, 1);
  674. }
  675. // 清理敌人身上的所有灼烧效果,防止定时器继续运行
  676. try {
  677. const burnEffect = enemy.getComponent(BurnEffect);
  678. if (burnEffect) {
  679. console.log(`[EnemyController] 清理敌人身上的灼烧效果`);
  680. // 先停止灼烧效果,再移除组件
  681. burnEffect.stopBurnEffect();
  682. enemy.removeComponent(BurnEffect);
  683. }
  684. } catch (error) {
  685. console.warn(`[EnemyController] 清理灼烧效果时出错:`, error);
  686. }
  687. // 敌人死亡时不在这里更新数量显示,由GameManager统一管理
  688. // 延迟销毁敌人,避免在物理碰撞监听器中直接销毁导致的刚体激活错误
  689. this.scheduleOnce(() => {
  690. if (enemy && enemy.isValid) {
  691. enemy.destroy();
  692. }
  693. }, 0);
  694. }
  695. }
  696. // 墙体受到伤害 - 现在委托给Wall组件
  697. damageWall(damage: number) {
  698. if (this.wallComponent) {
  699. this.wallComponent.takeDamage(damage);
  700. } else {
  701. console.warn('[EnemyController] 墙体组件未找到,无法处理伤害');
  702. }
  703. }
  704. // 游戏结束
  705. gameOver() {
  706. // 停止游戏,但不清除敌人
  707. this.stopGame(false);
  708. // 通过事件系统触发游戏失败
  709. const eventBus = EventBus.getInstance();
  710. eventBus.emit(GameEvents.GAME_DEFEAT);
  711. }
  712. update(dt: number) {
  713. if (!this.gameStarted) return;
  714. // 更新所有敌人
  715. for (let i = this.activeEnemies.length - 1; i >= 0; i--) {
  716. const enemy = this.activeEnemies[i];
  717. if (!enemy || !enemy.isValid) {
  718. this.activeEnemies.splice(i, 1);
  719. continue;
  720. }
  721. // 敌人更新由各自的组件处理
  722. // 不再需要检查敌人是否到达墙体,因为敌人到达游戏区域后会自动攻击
  723. // 敌人的攻击逻辑已经在EnemyInstance中处理
  724. }
  725. }
  726. public getCurrentWallHealth(): number {
  727. return this.wallComponent ? this.wallComponent.getCurrentHealth() : 0;
  728. }
  729. public forceEnemyAttack() {
  730. const activeEnemies = this.getActiveEnemies();
  731. for (const enemy of activeEnemies) {
  732. const enemyComp = enemy.getComponent(EnemyInstance);
  733. if (enemyComp) {
  734. // 直接调用damageWall方法进行测试
  735. this.damageWall(enemyComp.attackPower);
  736. }
  737. }
  738. }
  739. /** 供 EnemyInstance 在 onDestroy 中调用 */
  740. public notifyEnemyDead(enemyNode?: Node) {
  741. // 如果正在清理敌人,不触发任何游戏事件
  742. if (this.isClearing) {
  743. if (enemyNode) {
  744. const idx = this.activeEnemies.indexOf(enemyNode);
  745. if (idx !== -1) {
  746. this.activeEnemies.splice(idx, 1);
  747. }
  748. }
  749. return;
  750. }
  751. if (enemyNode) {
  752. const idx = this.activeEnemies.indexOf(enemyNode);
  753. if (idx !== -1) {
  754. this.activeEnemies.splice(idx, 1);
  755. } else {
  756. console.log(`[EnemyController] 警告:尝试移除的敌人不在activeEnemies数组中!`);
  757. }
  758. // 移除EnemyController内部的击杀计数,统一由GameManager管理
  759. // this.currentWaveEnemiesKilled++;
  760. // 敌人死亡通知时不更新数量显示,由GameManager统一管理
  761. }
  762. // 直接通过事件总线发送ENEMY_KILLED事件,避免通过GamePause的双重调用
  763. const eventBus = EventBus.getInstance();
  764. eventBus.emit('ENEMY_KILLED');
  765. }
  766. /**
  767. * 加载敌人骨骼动画
  768. */
  769. private loadEnemyAnimation(enemyNode: Node, enemyConfig: EnemyConfig) {
  770. console.log(`[EnemyController] 开始加载敌人动画,敌人ID: ${enemyConfig?.id}, 敌人名称: ${enemyConfig?.name}`);
  771. if (!enemyConfig || !enemyConfig.visualConfig) {
  772. console.warn('[EnemyController] 敌人配置或视觉配置缺失,使用默认动画');
  773. return;
  774. }
  775. let spinePath: string | undefined = enemyConfig.visualConfig?.spritePath;
  776. console.log(`[EnemyController] 敌人 ${enemyConfig.id} 的spritePath: ${spinePath}`);
  777. if (!spinePath) {
  778. console.warn('[EnemyController] 敌人精灵路径缺失');
  779. return;
  780. }
  781. if (spinePath.startsWith('@EnemyAni')) {
  782. spinePath = spinePath.replace('@EnemyAni', 'Animation/EnemyAni');
  783. }
  784. if (spinePath.startsWith('@')) {
  785. spinePath = spinePath.substring(1);
  786. }
  787. // 对于Animation/EnemyAni路径,需要添加子目录和文件名
  788. // 例如:Animation/EnemyAni/007 -> Animation/EnemyAni/007/007
  789. if (spinePath.startsWith('Animation/EnemyAni/')) {
  790. const parts = spinePath.split('/');
  791. if (parts.length === 3) {
  792. const animId = parts[2];
  793. spinePath = `${spinePath}/${animId}`;
  794. }
  795. }
  796. console.log(`[EnemyController] 最终加载路径: ${spinePath}`);
  797. resources.load(spinePath, sp.SkeletonData, (err, skeletonData) => {
  798. if (err) {
  799. console.warn(`加载敌人Spine动画失败: ${spinePath}`, err);
  800. return;
  801. }
  802. let skeleton = enemyNode.getComponent(sp.Skeleton);
  803. if (!skeleton) {
  804. skeleton = enemyNode.addComponent(sp.Skeleton);
  805. }
  806. skeleton.skeletonData = skeletonData;
  807. const anims = enemyConfig.visualConfig.animations;
  808. const walkName = anims?.walk ?? 'walk';
  809. const idleName = anims?.idle ?? 'idle';
  810. if (skeleton.findAnimation(walkName)) {
  811. skeleton.setAnimation(0, walkName, true);
  812. } else if (skeleton.findAnimation(idleName)) {
  813. skeleton.setAnimation(0, idleName, true);
  814. } else {
  815. console.warn(`[EnemyController] 未找到合适的动画,walk: ${walkName}, idle: ${idleName}`);
  816. }
  817. });
  818. }
  819. // 更新敌人数量显示
  820. public updateEnemyCountLabel(killedCount?: number) {
  821. if (!this.enemyCountLabelNode) {
  822. console.warn('[EnemyController] enemyCountLabelNode 未找到,无法更新敌人数量显示');
  823. return;
  824. }
  825. const label = this.enemyCountLabelNode.getComponent(Label);
  826. if (label) {
  827. // 计算剩余敌人数量:总数 - 击杀数量
  828. let remaining: number;
  829. if (killedCount !== undefined) {
  830. // 使用传入的击杀数量计算剩余数量
  831. remaining = Math.max(0, this.currentWaveTotalEnemies - killedCount);
  832. } else {
  833. // 如果没有传入击杀数量,则显示当前波次总敌人数(初始状态)
  834. remaining = this.currentWaveTotalEnemies;
  835. }
  836. label.string = remaining.toString();
  837. } else {
  838. console.warn('[EnemyController] enemyCountLabelNode 上未找到 Label 组件');
  839. }
  840. }
  841. public startWave(waveNum: number, totalWaves: number, totalEnemies: number, waveEnemyConfigs?: any[]) {
  842. this.currentWave = waveNum;
  843. this.totalWaves = totalWaves;
  844. this.currentWaveTotalEnemies = totalEnemies;
  845. this.currentWaveEnemiesSpawned = 0; // 重置已生成敌人计数器
  846. this.currentWaveEnemyConfigs = waveEnemyConfigs || []; // 存储当前波次的敌人配置
  847. // 移除EnemyController内部的击杀计数重置,统一由GameManager管理
  848. // this.currentWaveEnemiesKilled = 0;
  849. // 修复问题1:根据波次配置设置生成间隔
  850. if (this.currentWaveEnemyConfigs.length > 0) {
  851. // 使用第一个敌人配置的spawnInterval,如果有多个配置可以取平均值或最小值
  852. const firstEnemyConfig = this.currentWaveEnemyConfigs[0];
  853. if (firstEnemyConfig && typeof firstEnemyConfig.spawnInterval === 'number') {
  854. this.spawnInterval = firstEnemyConfig.spawnInterval;
  855. console.log(`[EnemyController] 设置生成间隔为: ${this.spawnInterval}`);
  856. }
  857. }
  858. console.log(`[EnemyController] 开始波次 ${waveNum}/${totalWaves},需要生成 ${totalEnemies} 个敌人`);
  859. console.log(`[EnemyController] 波次敌人配置:`, this.currentWaveEnemyConfigs);
  860. console.log(`[EnemyController] 当前生成间隔: ${this.spawnInterval}`);
  861. this.updateWaveLabel();
  862. this.updateEnemyCountLabel();
  863. // 移除startWaveUI的隐藏,因为现在使用Toast预制体
  864. // if (this.startWaveUI) this.startWaveUI.active = false;
  865. }
  866. private updateWaveLabel() {
  867. if (!this.waveNumberLabelNode) {
  868. console.warn('[EnemyController] waveNumberLabelNode 未找到,无法更新波次标签');
  869. return;
  870. }
  871. const label = this.waveNumberLabelNode.getComponent(Label);
  872. if (label) {
  873. const newText = `${this.currentWave}/${this.totalWaves}`;
  874. label.string = newText;
  875. } else {
  876. console.warn('[EnemyController] waveNumberLabelNode 上未找到 Label 组件');
  877. }
  878. }
  879. /** 显示每波开始提示,随后开启敌人生成 */
  880. public showStartWavePromptUI(duration: number = 2) {
  881. // 通过事件系统检查游戏是否已经结束
  882. let gameOver = false;
  883. EventBus.getInstance().emit(GameEvents.GAME_CHECK_OVER, (isOver: boolean) => {
  884. gameOver = isOver;
  885. });
  886. if (gameOver) {
  887. return;
  888. }
  889. // 使用事件机制显示Toast
  890. const toastText = `第${this.currentWave}波敌人来袭!`;
  891. EventBus.getInstance().emit(GameEvents.SHOW_TOAST, {
  892. message: toastText,
  893. duration: duration
  894. });
  895. // 暂停生成(确保未重复)
  896. this.pauseSpawning();
  897. if (duration > 0) {
  898. this.scheduleOnce(() => {
  899. // 再次通过事件系统检查游戏是否已经结束
  900. let gameOverCheck = false;
  901. EventBus.getInstance().emit(GameEvents.GAME_CHECK_OVER, (isOver: boolean) => {
  902. gameOverCheck = isOver;
  903. });
  904. if (gameOverCheck) {
  905. return;
  906. }
  907. // 真正开始/恢复生成敌人
  908. this.startGame();
  909. }, duration);
  910. } else {
  911. // 立即开始游戏
  912. this.startGame();
  913. }
  914. }
  915. /**
  916. * 重置到初始状态
  917. * 用于游戏重新开始时重置所有敌人相关状态
  918. */
  919. public resetToInitialState(): void {
  920. // 停止游戏并清理所有敌人
  921. this.stopGame(true);
  922. // 重置波次信息
  923. this.currentWave = 1;
  924. this.totalWaves = 1;
  925. this.currentWaveTotalEnemies = 0;
  926. this.currentWaveEnemiesKilled = 0;
  927. this.currentWaveEnemiesSpawned = 0;
  928. this.currentWaveEnemyConfigs = [];
  929. // 重置血量倍率
  930. this.currentHealthMultiplier = 1.0;
  931. // 清空暂停状态
  932. this.pausedEnemyStates.clear();
  933. // 重置UI显示
  934. this.updateEnemyCountLabel();
  935. this.updateWaveLabel();
  936. }
  937. /**
  938. * 处理更新敌人计数事件
  939. */
  940. private onUpdateEnemyCountEvent(killedCount: number) {
  941. this.updateEnemyCountLabel(killedCount);
  942. }
  943. /**
  944. * 处理启动波次事件
  945. */
  946. private onStartWaveEvent(data: { wave: number; totalWaves: number; enemyCount: number; waveEnemyConfigs: any[] }) {
  947. this.startWave(data.wave, data.totalWaves, data.enemyCount, data.waveEnemyConfigs);
  948. }
  949. /**
  950. * 处理启动游戏事件
  951. */
  952. private onStartGameEvent() {
  953. this.startGame();
  954. }
  955. /**
  956. * 处理显示波次提示事件
  957. */
  958. private onShowStartWavePromptEvent() {
  959. this.showStartWavePromptUI();
  960. }
  961. onDestroy() {
  962. // 清理事件监听
  963. const eventBus = EventBus.getInstance();
  964. eventBus.off(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
  965. eventBus.off(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  966. eventBus.off(GameEvents.GAME_SUCCESS, this.onGameEndEvent, this);
  967. eventBus.off(GameEvents.GAME_DEFEAT, this.onGameEndEvent, this);
  968. eventBus.off(GameEvents.CLEAR_ALL_GAME_OBJECTS, this.onClearAllGameObjectsEvent, this);
  969. eventBus.off(GameEvents.RESET_ENEMY_CONTROLLER, this.onResetEnemyControllerEvent, this);
  970. // 清理新增的事件监听
  971. eventBus.off(GameEvents.ENEMY_UPDATE_COUNT, this.onUpdateEnemyCountEvent, this);
  972. eventBus.off(GameEvents.ENEMY_START_WAVE, this.onStartWaveEvent, this);
  973. eventBus.off(GameEvents.ENEMY_START_GAME, this.onStartGameEvent, this);
  974. eventBus.off(GameEvents.ENEMY_SHOW_START_WAVE_PROMPT, this.onShowStartWavePromptEvent, this);
  975. // 清空状态
  976. this.pausedEnemyStates.clear();
  977. }
  978. }