EnemyController.ts 40 KB

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