EnemyController.ts 19 KB

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