EnemyController.ts 42 KB

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