EnemyController.ts 38 KB

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