EnemyController.ts 43 KB

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