EnemyController.ts 19 KB

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