EnemyController.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. import { _decorator, Node, Label, Vec3, Prefab, instantiate, find, UITransform, resources } 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. const { ccclass, property } = _decorator;
  9. // 前向声明EnemyInstance类型,避免循环引用
  10. class EnemyInstanceType {
  11. public health: number;
  12. public maxHealth: number;
  13. public speed: number;
  14. public attackPower: number;
  15. public movingDirection: number;
  16. public targetY: number;
  17. public changeDirectionTime: number;
  18. public controller: any;
  19. public node: Node;
  20. public updateHealthDisplay: () => void;
  21. public takeDamage: (damage: number) => void;
  22. }
  23. @ccclass('EnemyController')
  24. export class EnemyController extends BaseSingleton {
  25. // 仅类型声明,实例由 BaseSingleton 维护
  26. public static _instance: EnemyController;
  27. // 敌人预制体
  28. @property({
  29. type: Prefab,
  30. tooltip: '拖拽Enemy预制体到这里'
  31. })
  32. public enemyPrefab: Prefab = null;
  33. // 敌人容器节点
  34. @property({
  35. type: Node,
  36. tooltip: '拖拽enemyContainer节点到这里(Canvas/GameLevelUI/enemyContainer)'
  37. })
  38. public enemyContainer: Node = null;
  39. // === 生成 & 属性参数(保留需要可在内部自行设定,Inspector 不再显示) ===
  40. private spawnInterval: number = 3;
  41. // === 默认数值(当配置文件尚未加载时使用) ===
  42. private defaultEnemySpeed: number = 50;
  43. private defaultAttackPower: number = 10;
  44. private defaultHealth: number = 30;
  45. // 墙体属性
  46. @property({
  47. tooltip: '墙体初始血量'
  48. })
  49. public wallHealth: number = 1200;
  50. // 墙体血量显示节点(运行时动态查找)
  51. private wallHealthNode: Node = null;
  52. // 游戏区域边界 - 改为public,让敌人实例可以访问
  53. public gameBounds = {
  54. left: 0,
  55. right: 0,
  56. top: 0,
  57. bottom: 0
  58. };
  59. // 活跃的敌人列表
  60. private activeEnemies: Node[] = [];
  61. // 游戏是否已开始
  62. private gameStarted: boolean = false;
  63. // 墙体节点
  64. private wallNodes: Node[] = [];
  65. // 私有属性
  66. private gameManager: any = null;
  67. // 配置管理器
  68. private configManager: ConfigManager = null;
  69. @property({
  70. type: Node,
  71. tooltip: '敌人数量显示节点 (EnemyNumber)'
  72. })
  73. public enemyCountLabelNode: Node = null;
  74. @property({
  75. type: Node,
  76. tooltip: '波数显示Label (WaveNumber)'
  77. })
  78. public waveNumberLabelNode: Node = null;
  79. @property({
  80. type: Node,
  81. tooltip: '下一波提示UI节点 (NextWaveUI)'
  82. })
  83. public nextWaveUI: Node = null;
  84. private totalWaves: number = 1;
  85. private currentWave: number = 1;
  86. private currentWaveTotalEnemies: number = 0;
  87. private currentWaveEnemiesKilled: number = 0;
  88. /**
  89. * BaseSingleton 首次实例化回调
  90. */
  91. protected init() {
  92. // 获取配置管理器实例
  93. this.configManager = ConfigManager.getInstance();
  94. // 如果没有指定enemyContainer,尝试找到它
  95. if (!this.enemyContainer) {
  96. this.enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  97. if (!this.enemyContainer) {
  98. console.warn('找不到enemyContainer节点,将尝试创建');
  99. }
  100. }
  101. // 获取游戏区域边界
  102. this.calculateGameBounds();
  103. // 查找墙体节点
  104. this.findWallNodes();
  105. // 从存档读取墙体基础血量,如果有的话
  106. const sdm = SaveDataManager.getInstance();
  107. const base = (sdm.getPlayerData() as any)?.wallBaseHealth;
  108. if (typeof base === 'number' && base > 0) this.wallHealth = base;
  109. // 初始化墙体血量显示
  110. this.initWallHealthDisplay();
  111. // 确保enemyContainer节点存在
  112. this.ensureEnemyContainer();
  113. // 查找GameManager
  114. this.findGameManager();
  115. // 如果没有指定enemyCountLabelNode,尝试找到它
  116. if (!this.enemyCountLabelNode) {
  117. this.enemyCountLabelNode = find('Canvas/GameLevelUI/EnemyNode/EnemyNumber');
  118. }
  119. if (!this.waveNumberLabelNode) {
  120. this.waveNumberLabelNode = find('Canvas/GameLevelUI/WaveInfo/WaveNumber');
  121. }
  122. if (!this.nextWaveUI) {
  123. this.nextWaveUI = find('Canvas/GameLevelUI/NextWaveUI');
  124. }
  125. // 初始化敌人数量显示
  126. this.updateEnemyCountLabel();
  127. }
  128. // 计算游戏区域边界
  129. private calculateGameBounds() {
  130. const gameArea = find('Canvas/GameLevelUI/GameArea');
  131. if (!gameArea) {
  132. return;
  133. }
  134. const uiTransform = gameArea.getComponent(UITransform);
  135. if (!uiTransform) {
  136. return;
  137. }
  138. const worldPos = gameArea.worldPosition;
  139. const width = uiTransform.width;
  140. const height = uiTransform.height;
  141. this.gameBounds = {
  142. left: worldPos.x - width / 2,
  143. right: worldPos.x + width / 2,
  144. top: worldPos.y + height / 2,
  145. bottom: worldPos.y - height / 2
  146. };
  147. }
  148. // 查找墙体节点
  149. private findWallNodes() {
  150. const gameArea = find('Canvas/GameLevelUI/GameArea');
  151. if (gameArea) {
  152. this.wallNodes = [];
  153. for (let i = 0; i < gameArea.children.length; i++) {
  154. const child = gameArea.children[i];
  155. if (child.name.includes('Wall') || child.name.includes('wall') || child.name.includes('墙')) {
  156. this.wallNodes.push(child);
  157. }
  158. }
  159. }
  160. }
  161. // 初始化墙体血量显示
  162. initWallHealthDisplay() {
  163. if (!this.wallHealthNode) {
  164. // 尝试查找墙体血量显示节点
  165. this.wallHealthNode = find('Canvas/GameLevelUI/HeartNode');
  166. }
  167. if (this.wallHealthNode) {
  168. // 更新墙体血量显示
  169. this.updateWallHealthDisplay();
  170. } else {
  171. console.warn('未设置墙体血量显示节点');
  172. }
  173. }
  174. // 更新墙体血量显示
  175. public updateWallHealthDisplay() {
  176. if (!this.wallHealthNode) {
  177. return;
  178. }
  179. const heartLabel = this.wallHealthNode.getComponent(Label);
  180. if (heartLabel) {
  181. heartLabel.string = this.wallHealth.toString();
  182. }
  183. }
  184. // 确保enemyContainer节点存在
  185. ensureEnemyContainer() {
  186. // 如果已经通过拖拽设置了节点,直接使用
  187. if (this.enemyContainer && this.enemyContainer.isValid) {
  188. return;
  189. }
  190. // 尝试查找节点
  191. this.enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  192. if (this.enemyContainer) {
  193. console.log('找到已存在的enemyContainer节点');
  194. return;
  195. }
  196. // 如果找不到,创建新节点
  197. const gameLevelUI = find('Canvas/GameLevelUI');
  198. if (!gameLevelUI) {
  199. console.error('找不到GameLevelUI节点,无法创建enemyContainer');
  200. return;
  201. }
  202. this.enemyContainer = new Node('enemyContainer');
  203. gameLevelUI.addChild(this.enemyContainer);
  204. if (!this.enemyContainer.getComponent(UITransform)) {
  205. this.enemyContainer.addComponent(UITransform);
  206. }
  207. console.log('已在GameLevelUI下创建enemyContainer节点');
  208. }
  209. // 游戏开始
  210. startGame() {
  211. this.gameStarted = true;
  212. // 确保enemyContainer节点存在
  213. this.ensureEnemyContainer();
  214. // 开始生成敌人
  215. this.schedule(this.spawnEnemy, this.spawnInterval);
  216. console.log('开始生成敌人');
  217. }
  218. // 游戏结束
  219. stopGame() {
  220. this.gameStarted = false;
  221. // 停止生成敌人
  222. this.unschedule(this.spawnEnemy);
  223. // 清除所有敌人
  224. this.clearAllEnemies();
  225. console.log('停止生成敌人');
  226. }
  227. // 生成敌人
  228. spawnEnemy() {
  229. if (!this.gameStarted || !this.enemyPrefab) return;
  230. // 随机决定从上方还是下方生成
  231. const fromTop = Math.random() > 0.5;
  232. // 实例化敌人
  233. const enemy = instantiate(this.enemyPrefab);
  234. enemy.name = 'Enemy'; // 确保敌人节点名称为Enemy
  235. // 添加到场景中
  236. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  237. if (!enemyContainer) {
  238. return;
  239. }
  240. enemyContainer.addChild(enemy);
  241. // 设置敌人位置
  242. const xPos = this.gameBounds.left + Math.random() * (this.gameBounds.right - this.gameBounds.left);
  243. const yPos = fromTop ? this.gameBounds.top + 100 : this.gameBounds.bottom - 100;
  244. // 将世界坐标转换为相对于enemyContainer的本地坐标
  245. const localPos = enemyContainer.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(xPos, yPos, 0));
  246. enemy.position = localPos;
  247. // === 根据配置设置敌人 ===
  248. const enemyComp = enemy.addComponent(EnemyInstance);
  249. let enemyConfig: EnemyConfig = null;
  250. if (this.configManager && this.configManager.isConfigLoaded()) {
  251. enemyConfig = this.configManager.getRandomEnemy();
  252. }
  253. if (enemyConfig) {
  254. // 添加EnemyComponent保存配置
  255. const cfgComp = enemy.addComponent(EnemyComponent);
  256. cfgComp.enemyConfig = enemyConfig;
  257. cfgComp.spawner = this;
  258. // 应用数值
  259. enemyComp.health = enemyConfig.stats.health;
  260. enemyComp.maxHealth = enemyConfig.stats.health;
  261. enemyComp.speed = enemyConfig.stats.speed;
  262. enemyComp.attackPower = enemyConfig.stats.damage;
  263. // 加载动画
  264. this.loadEnemyAnimation(enemy, enemyConfig);
  265. } else {
  266. // 使用默认值
  267. enemyComp.health = this.defaultHealth;
  268. enemyComp.maxHealth = this.defaultHealth;
  269. enemyComp.speed = this.defaultEnemySpeed;
  270. enemyComp.attackPower = this.defaultAttackPower;
  271. }
  272. enemyComp.movingDirection = Math.random() > 0.5 ? 1 : -1;
  273. enemyComp.targetY = fromTop ? this.gameBounds.top - 50 : this.gameBounds.bottom + 50;
  274. enemyComp.changeDirectionTime = 0;
  275. enemyComp.controller = this;
  276. // 更新敌人血量显示
  277. enemyComp.updateHealthDisplay();
  278. // 添加到活跃敌人列表
  279. this.activeEnemies.push(enemy);
  280. // 更新敌人数量显示
  281. this.updateEnemyCountLabel();
  282. console.log(`生成敌人,当前共有 ${this.activeEnemies.length} 个敌人`);
  283. }
  284. // 清除所有敌人
  285. clearAllEnemies() {
  286. for (const enemy of this.activeEnemies) {
  287. if (enemy && enemy.isValid) {
  288. enemy.destroy();
  289. }
  290. }
  291. this.activeEnemies = [];
  292. // 更新敌人数量显示
  293. this.updateEnemyCountLabel();
  294. }
  295. // 获取所有活跃的敌人
  296. getActiveEnemies(): Node[] {
  297. // 过滤掉已经无效的敌人
  298. this.activeEnemies = this.activeEnemies.filter(enemy => enemy && enemy.isValid);
  299. return this.activeEnemies;
  300. }
  301. // 获取当前敌人数量
  302. getCurrentEnemyCount(): number {
  303. return this.getActiveEnemies().length;
  304. }
  305. // 获取游戏是否已开始状态
  306. public isGameStarted(): boolean {
  307. return this.gameStarted;
  308. }
  309. // 暂停生成敌人
  310. public pauseSpawning(): void {
  311. if (this.gameStarted) {
  312. this.unschedule(this.spawnEnemy);
  313. }
  314. }
  315. // 恢复生成敌人
  316. public resumeSpawning(): void {
  317. if (this.gameStarted) {
  318. this.schedule(this.spawnEnemy, this.spawnInterval);
  319. }
  320. }
  321. // 敌人受到伤害
  322. damageEnemy(enemy: Node, damage: number) {
  323. if (!enemy || !enemy.isValid) return;
  324. // 获取敌人组件
  325. const enemyComp = enemy.getComponent(EnemyInstance);
  326. if (!enemyComp) return;
  327. // 减少敌人血量
  328. enemyComp.takeDamage(damage);
  329. // 检查敌人是否死亡
  330. if (enemyComp.health <= 0) {
  331. // 从活跃敌人列表中移除
  332. const index = this.activeEnemies.indexOf(enemy);
  333. if (index !== -1) {
  334. this.activeEnemies.splice(index, 1);
  335. }
  336. // 更新敌人数量显示
  337. this.updateEnemyCountLabel();
  338. // 销毁敌人
  339. enemy.destroy();
  340. }
  341. }
  342. // 墙体受到伤害
  343. damageWall(damage: number) {
  344. // 减少墙体血量
  345. this.wallHealth -= damage;
  346. // 更新墙体血量显示
  347. this.updateWallHealthDisplay();
  348. // 检查墙体是否被摧毁
  349. if (this.wallHealth <= 0) {
  350. // 游戏结束
  351. this.gameOver();
  352. }
  353. }
  354. // 游戏结束
  355. gameOver() {
  356. // 停止游戏
  357. this.stopGame();
  358. // 通知GameManager游戏结束
  359. const gameManagerNode = find('Canvas/GameLevelUI/GameManager');
  360. if (gameManagerNode) {
  361. const gameManager = gameManagerNode.getComponent('GameManager') as any;
  362. if (gameManager) {
  363. gameManager.gameOver();
  364. }
  365. }
  366. }
  367. update(dt: number) {
  368. if (!this.gameStarted) return;
  369. // 更新所有敌人
  370. for (let i = this.activeEnemies.length - 1; i >= 0; i--) {
  371. const enemy = this.activeEnemies[i];
  372. if (!enemy || !enemy.isValid) {
  373. this.activeEnemies.splice(i, 1);
  374. continue;
  375. }
  376. // 敌人更新由各自的组件处理
  377. // 不再需要检查敌人是否到达墙体,因为敌人到达游戏区域后会自动攻击
  378. // 敌人的攻击逻辑已经在EnemyInstance中处理
  379. }
  380. }
  381. // === 调试方法 ===
  382. public testEnemyAttack() {
  383. console.log('=== 测试敌人攻击墙体 ===');
  384. // 手动触发墙体受到伤害
  385. const testDamage = 50;
  386. console.log(`模拟敌人攻击,伤害: ${testDamage}`);
  387. this.damageWall(testDamage);
  388. return this.wallHealth;
  389. }
  390. public getCurrentWallHealth(): number {
  391. return this.wallHealth;
  392. }
  393. public forceEnemyAttack() {
  394. console.log('=== 强制所有敌人进入攻击状态 ===');
  395. const activeEnemies = this.getActiveEnemies();
  396. console.log(`当前活跃敌人数量: ${activeEnemies.length}`);
  397. for (const enemy of activeEnemies) {
  398. const enemyComp = enemy.getComponent(EnemyInstance);
  399. if (enemyComp) {
  400. console.log(`强制敌人 ${enemy.name} 进入攻击状态`);
  401. // 直接调用damageWall方法进行测试
  402. this.damageWall(enemyComp.attackPower);
  403. }
  404. }
  405. }
  406. // === 查找GameManager ===
  407. private findGameManager() {
  408. const gameManagerNode = find('Canvas/GameLevelUI/GameManager');
  409. if (gameManagerNode) {
  410. this.gameManager = gameManagerNode.getComponent('GameManager');
  411. }
  412. }
  413. /** 供 EnemyInstance 在 onDestroy 中调用 */
  414. public notifyEnemyDead(enemyNode?: Node) {
  415. if (enemyNode) {
  416. const idx = this.activeEnemies.indexOf(enemyNode);
  417. if (idx !== -1) this.activeEnemies.splice(idx, 1);
  418. this.currentWaveEnemiesKilled++;
  419. this.updateEnemyCountLabel();
  420. }
  421. if (this.gameManager && this.gameManager.onEnemyKilled) {
  422. this.gameManager.onEnemyKilled();
  423. }
  424. }
  425. /**
  426. * 加载敌人骨骼动画
  427. */
  428. private loadEnemyAnimation(enemyNode: Node, enemyConfig: EnemyConfig) {
  429. let spinePath: string | undefined = enemyConfig.visualConfig?.spritePrefab;
  430. if (!spinePath) return;
  431. if (spinePath.startsWith('@EnemyAni')) {
  432. spinePath = spinePath.replace('@EnemyAni', 'Animation/EnemyAni');
  433. }
  434. if (spinePath.startsWith('@')) {
  435. spinePath = spinePath.substring(1);
  436. }
  437. resources.load(spinePath, sp.SkeletonData, (err, skeletonData) => {
  438. if (err) {
  439. console.warn(`加载敌人Spine动画失败: ${spinePath}`, err);
  440. return;
  441. }
  442. let skeleton = enemyNode.getComponent(sp.Skeleton);
  443. if (!skeleton) {
  444. skeleton = enemyNode.addComponent(sp.Skeleton);
  445. }
  446. skeleton.skeletonData = skeletonData;
  447. const anims = enemyConfig.visualConfig.animations;
  448. const walkName = anims?.walk ?? 'walk';
  449. const idleName = anims?.idle ?? 'idle';
  450. if (skeleton.findAnimation(walkName)) {
  451. skeleton.setAnimation(0, walkName, true);
  452. } else if (skeleton.findAnimation(idleName)) {
  453. skeleton.setAnimation(0, idleName, true);
  454. }
  455. });
  456. }
  457. // 更新敌人数量显示
  458. private updateEnemyCountLabel() {
  459. if (!this.enemyCountLabelNode) return;
  460. const label = this.enemyCountLabelNode.getComponent(Label);
  461. if (label) {
  462. const remaining = Math.max(0, this.currentWaveTotalEnemies - this.currentWaveEnemiesKilled);
  463. label.string = remaining.toString();
  464. console.log(`EnemyController 剩余敌人数量: ${remaining}`);
  465. }
  466. }
  467. public startWave(waveNum: number, totalWaves: number, totalEnemies: number) {
  468. this.currentWave = waveNum;
  469. this.totalWaves = totalWaves;
  470. this.currentWaveTotalEnemies = totalEnemies;
  471. this.currentWaveEnemiesKilled = 0;
  472. this.updateWaveLabel();
  473. this.updateEnemyCountLabel();
  474. if (this.nextWaveUI) this.nextWaveUI.active = false;
  475. }
  476. private updateWaveLabel() {
  477. if (!this.waveNumberLabelNode) return;
  478. const label = this.waveNumberLabelNode.getComponent(Label);
  479. if (label) {
  480. label.string = `${this.currentWave}/${this.totalWaves}`;
  481. }
  482. }
  483. public showNextWavePromptUI(duration: number = 2) {
  484. if (!this.nextWaveUI) return;
  485. this.nextWaveUI.active = true;
  486. if (duration > 0) {
  487. this.scheduleOnce(() => {
  488. if (this.nextWaveUI) this.nextWaveUI.active = false;
  489. }, duration);
  490. }
  491. }
  492. }