EnemyController.ts 43 KB

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