EnemyController.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. import { _decorator, Component, Node, ProgressBar, Label, Vec3, Prefab, instantiate, find, UITransform, BoxCollider2D, RigidBody2D, ERigidBody2DType } from 'cc';
  2. import { EnemyInstance } from './EnemyInstance';
  3. const { ccclass, property } = _decorator;
  4. // 前向声明EnemyInstance类型,避免循环引用
  5. class EnemyInstanceType {
  6. public health: number;
  7. public maxHealth: number;
  8. public speed: number;
  9. public attackPower: number;
  10. public movingDirection: number;
  11. public targetY: number;
  12. public changeDirectionTime: number;
  13. public controller: any;
  14. public node: Node;
  15. public updateHealthDisplay: () => void;
  16. public takeDamage: (damage: number) => void;
  17. }
  18. @ccclass('EnemyController')
  19. export class EnemyController extends Component {
  20. // 敌人预制体
  21. @property({
  22. type: Prefab,
  23. tooltip: '拖拽Enemy预制体到这里'
  24. })
  25. public enemyPrefab: Prefab = null;
  26. // 敌人生成参数
  27. @property({
  28. tooltip: '敌人生成间隔(秒)'
  29. })
  30. public spawnInterval: number = 3;
  31. // 敌人属性
  32. @property({
  33. tooltip: '敌人移动速度'
  34. })
  35. public enemySpeed: number = 50;
  36. @property({
  37. tooltip: '敌人攻击力'
  38. })
  39. public attackPower: number = 10;
  40. @property({
  41. tooltip: '敌人生命值'
  42. })
  43. public health: 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 enemyContainer: Node = null;
  69. private gameManager: any = null;
  70. start() {
  71. // 获取游戏区域边界
  72. this.calculateGameBounds();
  73. // 查找墙体节点
  74. this.findWallNodes();
  75. // 初始化墙体血量显示
  76. this.initWallHealthDisplay();
  77. // 确保enemyContainer节点存在
  78. this.ensureEnemyContainer();
  79. // 查找GameManager
  80. this.findGameManager();
  81. }
  82. // 计算游戏区域边界
  83. private calculateGameBounds() {
  84. const gameArea = find('Canvas/GameLevelUI/GameArea');
  85. if (!gameArea) {
  86. return;
  87. }
  88. const uiTransform = gameArea.getComponent(UITransform);
  89. if (!uiTransform) {
  90. return;
  91. }
  92. const worldPos = gameArea.worldPosition;
  93. const width = uiTransform.width;
  94. const height = uiTransform.height;
  95. this.gameBounds = {
  96. left: worldPos.x - width / 2,
  97. right: worldPos.x + width / 2,
  98. top: worldPos.y + height / 2,
  99. bottom: worldPos.y - height / 2
  100. };
  101. }
  102. // 查找墙体节点
  103. private findWallNodes() {
  104. const gameArea = find('Canvas/GameLevelUI/GameArea');
  105. if (gameArea) {
  106. this.wallNodes = [];
  107. for (let i = 0; i < gameArea.children.length; i++) {
  108. const child = gameArea.children[i];
  109. if (child.name.includes('Wall') || child.name.includes('wall') || child.name.includes('墙')) {
  110. this.wallNodes.push(child);
  111. }
  112. }
  113. }
  114. }
  115. // 初始化墙体血量显示
  116. initWallHealthDisplay() {
  117. if (!this.wallHealthNode) {
  118. // 尝试查找墙体血量显示节点
  119. this.wallHealthNode = find('Canvas/GameLevelUI/HeartNode');
  120. }
  121. if (this.wallHealthNode) {
  122. // 更新墙体血量显示
  123. this.updateWallHealthDisplay();
  124. } else {
  125. console.warn('未设置墙体血量显示节点');
  126. }
  127. }
  128. // 更新墙体血量显示
  129. public updateWallHealthDisplay() {
  130. if (!this.wallHealthNode) {
  131. return;
  132. }
  133. const heartLabel = this.wallHealthNode.getComponent(Label);
  134. if (heartLabel) {
  135. heartLabel.string = this.wallHealth.toString();
  136. }
  137. }
  138. // 确保enemyContainer节点存在
  139. ensureEnemyContainer() {
  140. const gameLevelUI = find('Canvas/GameLevelUI');
  141. if (!gameLevelUI) {
  142. return;
  143. }
  144. this.enemyContainer = gameLevelUI.getChildByName('enemyContainer');
  145. if (!this.enemyContainer) {
  146. this.enemyContainer = new Node('enemyContainer');
  147. gameLevelUI.addChild(this.enemyContainer);
  148. }
  149. }
  150. // 游戏开始
  151. startGame() {
  152. this.gameStarted = true;
  153. // 确保enemyContainer节点存在
  154. this.ensureEnemyContainer();
  155. // 开始生成敌人
  156. this.schedule(this.spawnEnemy, this.spawnInterval);
  157. console.log('开始生成敌人');
  158. }
  159. // 游戏结束
  160. stopGame() {
  161. this.gameStarted = false;
  162. // 停止生成敌人
  163. this.unschedule(this.spawnEnemy);
  164. // 清除所有敌人
  165. this.clearAllEnemies();
  166. console.log('停止生成敌人');
  167. }
  168. // 生成敌人
  169. spawnEnemy() {
  170. if (!this.gameStarted || !this.enemyPrefab) return;
  171. // 随机决定从上方还是下方生成
  172. const fromTop = Math.random() > 0.5;
  173. // 实例化敌人
  174. const enemy = instantiate(this.enemyPrefab);
  175. enemy.name = 'Enemy'; // 确保敌人节点名称为Enemy
  176. // 添加到场景中
  177. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  178. if (!enemyContainer) {
  179. return;
  180. }
  181. enemyContainer.addChild(enemy);
  182. // 设置敌人位置
  183. const xPos = this.gameBounds.left + Math.random() * (this.gameBounds.right - this.gameBounds.left);
  184. const yPos = fromTop ? this.gameBounds.top + 100 : this.gameBounds.bottom - 100;
  185. // 将世界坐标转换为相对于enemyContainer的本地坐标
  186. const localPos = enemyContainer.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(xPos, yPos, 0));
  187. enemy.position = localPos;
  188. // 设置敌人属性 - 直接使用组件而不是自定义属性
  189. const enemyComp = enemy.addComponent(EnemyInstance);
  190. enemyComp.health = this.health;
  191. enemyComp.maxHealth = this.health;
  192. enemyComp.speed = this.enemySpeed;
  193. enemyComp.attackPower = this.attackPower;
  194. enemyComp.movingDirection = Math.random() > 0.5 ? 1 : -1; // 随机初始移动方向
  195. enemyComp.targetY = fromTop ? this.gameBounds.top - 50 : this.gameBounds.bottom + 50; // 目标Y位置
  196. enemyComp.changeDirectionTime = 0; // 下次改变方向的时间
  197. enemyComp.controller = this; // 设置对控制器的引用
  198. // 更新敌人血量显示
  199. enemyComp.updateHealthDisplay();
  200. // 添加到活跃敌人列表
  201. this.activeEnemies.push(enemy);
  202. console.log(`生成敌人,当前共有 ${this.activeEnemies.length} 个敌人`);
  203. }
  204. // 清除所有敌人
  205. clearAllEnemies() {
  206. for (const enemy of this.activeEnemies) {
  207. if (enemy && enemy.isValid) {
  208. enemy.destroy();
  209. }
  210. }
  211. this.activeEnemies = [];
  212. }
  213. // 获取所有活跃的敌人
  214. getActiveEnemies(): Node[] {
  215. // 过滤掉已经无效的敌人
  216. this.activeEnemies = this.activeEnemies.filter(enemy => enemy && enemy.isValid);
  217. return this.activeEnemies;
  218. }
  219. // 获取当前敌人数量
  220. getCurrentEnemyCount(): number {
  221. return this.getActiveEnemies().length;
  222. }
  223. // 获取游戏是否已开始状态
  224. public isGameStarted(): boolean {
  225. return this.gameStarted;
  226. }
  227. // 暂停生成敌人
  228. public pauseSpawning(): void {
  229. if (this.gameStarted) {
  230. this.unschedule(this.spawnEnemy);
  231. }
  232. }
  233. // 恢复生成敌人
  234. public resumeSpawning(): void {
  235. if (this.gameStarted) {
  236. this.schedule(this.spawnEnemy, this.spawnInterval);
  237. }
  238. }
  239. // 敌人受到伤害
  240. damageEnemy(enemy: Node, damage: number) {
  241. if (!enemy || !enemy.isValid) return;
  242. // 获取敌人组件
  243. const enemyComp = enemy.getComponent(EnemyInstance);
  244. if (!enemyComp) return;
  245. // 减少敌人血量
  246. enemyComp.takeDamage(damage);
  247. // 检查敌人是否死亡
  248. if (enemyComp.health <= 0) {
  249. // 从活跃敌人列表中移除
  250. const index = this.activeEnemies.indexOf(enemy);
  251. if (index !== -1) {
  252. this.activeEnemies.splice(index, 1);
  253. }
  254. // 销毁敌人
  255. enemy.destroy();
  256. }
  257. }
  258. // 墙体受到伤害
  259. damageWall(damage: number) {
  260. // 减少墙体血量
  261. this.wallHealth -= damage;
  262. // 更新墙体血量显示
  263. this.updateWallHealthDisplay();
  264. // 检查墙体是否被摧毁
  265. if (this.wallHealth <= 0) {
  266. // 游戏结束
  267. this.gameOver();
  268. }
  269. }
  270. // 游戏结束
  271. gameOver() {
  272. // 停止游戏
  273. this.stopGame();
  274. // 通知GameManager游戏结束
  275. const gameManagerNode = find('Canvas/GameLevelUI/GameManager');
  276. if (gameManagerNode) {
  277. const gameManager = gameManagerNode.getComponent('GameManager') as any;
  278. if (gameManager) {
  279. gameManager.gameOver();
  280. }
  281. }
  282. }
  283. update(dt: number) {
  284. if (!this.gameStarted) return;
  285. // 更新所有敌人
  286. for (let i = this.activeEnemies.length - 1; i >= 0; i--) {
  287. const enemy = this.activeEnemies[i];
  288. if (!enemy || !enemy.isValid) {
  289. this.activeEnemies.splice(i, 1);
  290. continue;
  291. }
  292. // 敌人更新由各自的组件处理
  293. // 不再需要检查敌人是否到达墙体,因为敌人到达游戏区域后会自动攻击
  294. // 敌人的攻击逻辑已经在EnemyInstance中处理
  295. }
  296. }
  297. // === 调试方法 ===
  298. public testEnemyAttack() {
  299. console.log('=== 测试敌人攻击墙体 ===');
  300. // 手动触发墙体受到伤害
  301. const testDamage = 50;
  302. console.log(`模拟敌人攻击,伤害: ${testDamage}`);
  303. this.damageWall(testDamage);
  304. return this.wallHealth;
  305. }
  306. public getCurrentWallHealth(): number {
  307. return this.wallHealth;
  308. }
  309. public forceEnemyAttack() {
  310. console.log('=== 强制所有敌人进入攻击状态 ===');
  311. const activeEnemies = this.getActiveEnemies();
  312. console.log(`当前活跃敌人数量: ${activeEnemies.length}`);
  313. for (const enemy of activeEnemies) {
  314. const enemyComp = enemy.getComponent(EnemyInstance);
  315. if (enemyComp) {
  316. console.log(`强制敌人 ${enemy.name} 进入攻击状态`);
  317. // 直接调用damageWall方法进行测试
  318. this.damageWall(enemyComp.attackPower);
  319. }
  320. }
  321. }
  322. // === 查找GameManager ===
  323. private findGameManager() {
  324. const gameManagerNode = find('Canvas/GameLevelUI/GameManager');
  325. if (gameManagerNode) {
  326. this.gameManager = gameManagerNode.getComponent('GameManager');
  327. }
  328. }
  329. }