EnemyController.ts 18 KB

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