EnemyInstance.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. import { _decorator, Component, Node, ProgressBar, Label, Vec3, find, UITransform, Collider2D, Contact2DType, IPhysics2DContact, instantiate, resources, Prefab } from 'cc';
  2. import { sp } from 'cc';
  3. const { ccclass, property } = _decorator;
  4. // 前向声明EnemyController接口,避免循环引用
  5. interface EnemyControllerType {
  6. gameBounds: {
  7. left: number;
  8. right: number;
  9. top: number;
  10. bottom: number;
  11. };
  12. damageWall: (damage: number) => void;
  13. }
  14. // 敌人状态枚举
  15. enum EnemyState {
  16. MOVING, // 移动中
  17. ATTACKING, // 攻击中
  18. DEAD // 死亡
  19. }
  20. // 单个敌人实例的组件
  21. @ccclass('EnemyInstance')
  22. export class EnemyInstance extends Component {
  23. // 敌人属性
  24. public health: number = 30;
  25. public maxHealth: number = 30;
  26. public speed: number = 50;
  27. public attackPower: number = 10;
  28. // === 新增属性 ===
  29. /** 是否从上方生成 */
  30. public spawnFromTop: boolean = true;
  31. /** 目标 Fence 节点(TopFence / BottomFence) */
  32. public targetFence: Node | null = null;
  33. // 移动属性
  34. public movingDirection: number = 1; // 1: 向右, -1: 向左
  35. public targetY: number = 0; // 目标Y位置
  36. public changeDirectionTime: number = 0; // 下次改变方向的时间
  37. // 攻击属性
  38. public attackInterval: number = 2; // 攻击间隔(秒)
  39. private attackTimer: number = 0;
  40. // 对控制器的引用
  41. public controller: EnemyControllerType = null;
  42. // 敌人当前状态
  43. private state: EnemyState = EnemyState.MOVING;
  44. // 游戏区域中心
  45. private gameAreaCenter: Vec3 = new Vec3();
  46. // 碰撞的墙体
  47. private collidedWall: Node = null;
  48. // 骨骼动画组件
  49. private skeleton: sp.Skeleton | null = null;
  50. start() {
  51. // 初始化敌人
  52. this.initializeEnemy();
  53. }
  54. // 初始化敌人
  55. private initializeEnemy() {
  56. this.health = this.maxHealth;
  57. this.state = EnemyState.MOVING;
  58. if (this.speed === 0) this.speed = 50;
  59. if (this.attackPower === 0) this.attackPower = 10;
  60. this.attackInterval = 2.0; // 默认攻击间隔
  61. this.attackTimer = 0;
  62. // 获取骨骼动画组件
  63. this.skeleton = this.getComponent(sp.Skeleton);
  64. this.playWalkAnimation();
  65. // 计算游戏区域中心
  66. this.calculateGameAreaCenter();
  67. // 初始化碰撞检测
  68. this.setupCollider();
  69. }
  70. // 设置碰撞器
  71. setupCollider() {
  72. // 检查节点是否有碰撞器
  73. let collider = this.node.getComponent(Collider2D);
  74. if (!collider) {
  75. return;
  76. }
  77. // 设置碰撞事件监听
  78. collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  79. }
  80. // 碰撞开始事件
  81. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  82. const nodeName = otherCollider.node.name;
  83. // 如果碰到墙体,停止移动并开始攻击
  84. if (nodeName.includes('Wall') || nodeName.includes('wall') || nodeName.includes('Fence') || nodeName.includes('Jiguang')) {
  85. this.state = EnemyState.ATTACKING;
  86. this.attackTimer = 0; // 立即开始攻击
  87. // 切换攻击动画
  88. this.playAttackAnimation();
  89. }
  90. }
  91. // 获取节点路径
  92. getNodePath(node: Node): string {
  93. let path = node.name;
  94. let current = node;
  95. while (current.parent) {
  96. current = current.parent;
  97. path = current.name + '/' + path;
  98. }
  99. return path;
  100. }
  101. // 计算游戏区域中心
  102. private calculateGameAreaCenter() {
  103. const gameArea = find('Canvas/GameLevelUI/GameArea');
  104. if (gameArea) {
  105. this.gameAreaCenter = gameArea.worldPosition;
  106. }
  107. }
  108. // 更新血量显示
  109. updateHealthDisplay() {
  110. // 更新血条
  111. const hpBar = this.node.getChildByName('HPBar');
  112. if (hpBar) {
  113. const progressBar = hpBar.getComponent(ProgressBar);
  114. if (progressBar) {
  115. progressBar.progress = this.health / this.maxHealth;
  116. }
  117. }
  118. // 更新血量数字
  119. const hpLabel = this.node.getChildByName('HPLabel');
  120. if (hpLabel) {
  121. const label = hpLabel.getComponent(Label);
  122. if (label) {
  123. label.string = this.health.toString();
  124. }
  125. }
  126. }
  127. // 受到伤害
  128. takeDamage(damage: number) {
  129. // 如果已经死亡,不再处理伤害
  130. if (this.state === EnemyState.DEAD) {
  131. return;
  132. }
  133. this.health -= damage;
  134. console.log(`[EnemyInstance] 敌人受到伤害: ${damage}, 剩余血量: ${this.health}`);
  135. // 更新血量显示
  136. this.updateHealthDisplay();
  137. // 如果血量低于等于0,销毁敌人
  138. if (this.health <= 0) {
  139. console.log(`[EnemyInstance] 敌人死亡,开始销毁流程`);
  140. this.state = EnemyState.DEAD;
  141. this.spawnCoin();
  142. // 进入死亡流程,禁用碰撞避免重复命中
  143. const col = this.getComponent(Collider2D);
  144. if (col) col.enabled = false;
  145. this.playDeathAnimationAndDestroy();
  146. }
  147. }
  148. onDestroy() {
  149. console.log(`[EnemyInstance] onDestroy 被调用,准备通知控制器`);
  150. // 通知控制器 & GameManager
  151. if (this.controller && typeof (this.controller as any).notifyEnemyDead === 'function') {
  152. console.log(`[EnemyInstance] 调用 notifyEnemyDead`);
  153. (this.controller as any).notifyEnemyDead(this.node);
  154. } else {
  155. console.warn(`[EnemyInstance] 无法调用 notifyEnemyDead: controller=${!!this.controller}`);
  156. }
  157. }
  158. update(deltaTime: number) {
  159. if (this.state === EnemyState.MOVING) {
  160. this.updateMovement(deltaTime);
  161. } else if (this.state === EnemyState.ATTACKING) {
  162. this.updateAttack(deltaTime);
  163. }
  164. // 不再每帧播放攻击动画,避免日志刷屏
  165. }
  166. // 更新移动逻辑
  167. private updateMovement(deltaTime: number) {
  168. // 检查是否接近游戏区域边界
  169. if (this.checkNearGameArea()) {
  170. this.state = EnemyState.ATTACKING;
  171. this.attackTimer = 0;
  172. this.playAttackAnimation();
  173. return;
  174. }
  175. // 继续移动
  176. this.moveTowardsTarget(deltaTime);
  177. }
  178. // 检查是否接近游戏区域
  179. private checkNearGameArea(): boolean {
  180. const currentPos = this.node.worldPosition;
  181. // 获取游戏区域边界
  182. const gameArea = find('Canvas/GameLevelUI/GameArea');
  183. if (!gameArea) return false;
  184. const uiTransform = gameArea.getComponent(UITransform);
  185. if (!uiTransform) return false;
  186. const gameAreaPos = gameArea.worldPosition;
  187. const halfWidth = uiTransform.width / 2;
  188. const halfHeight = uiTransform.height / 2;
  189. const bounds = {
  190. left: gameAreaPos.x - halfWidth,
  191. right: gameAreaPos.x + halfWidth,
  192. top: gameAreaPos.y + halfHeight,
  193. bottom: gameAreaPos.y - halfHeight
  194. };
  195. // 检查是否在游戏区域内或非常接近
  196. const safeDistance = 50; // 安全距离
  197. const isInside = currentPos.x >= bounds.left - safeDistance &&
  198. currentPos.x <= bounds.right + safeDistance &&
  199. currentPos.y >= bounds.bottom - safeDistance &&
  200. currentPos.y <= bounds.top + safeDistance;
  201. if (isInside) {
  202. return true;
  203. }
  204. return false;
  205. }
  206. // 移动到目标位置
  207. private moveTowardsTarget(deltaTime: number) {
  208. // 使用世界坐标进行移动计算,确保不受父节点坐标系影响
  209. const currentWorldPos = this.node.worldPosition.clone();
  210. // 目标世界坐标:优先使用指定的 Fence,其次退化到游戏区域中心
  211. let targetWorldPos: Vec3;
  212. if (this.targetFence && this.targetFence.isValid) {
  213. targetWorldPos = this.targetFence.worldPosition.clone();
  214. } else {
  215. targetWorldPos = this.gameAreaCenter.clone();
  216. }
  217. const dir = targetWorldPos.subtract(currentWorldPos);
  218. if (dir.length() === 0) return;
  219. dir.normalize();
  220. const moveDistance = this.speed * deltaTime;
  221. const newWorldPos = currentWorldPos.add(dir.multiplyScalar(moveDistance));
  222. // 直接设置世界坐标
  223. this.node.setWorldPosition(newWorldPos);
  224. }
  225. // 更新攻击逻辑
  226. private updateAttack(deltaTime: number) {
  227. this.attackTimer -= deltaTime;
  228. if (this.attackTimer <= 0) {
  229. // 执行攻击
  230. this.performAttack();
  231. // 重置攻击计时器
  232. this.attackTimer = this.attackInterval;
  233. }
  234. }
  235. // 执行攻击
  236. private performAttack() {
  237. if (!this.controller) {
  238. return;
  239. }
  240. // 对墙体造成伤害
  241. this.controller.damageWall(this.attackPower);
  242. }
  243. // 播放行走动画
  244. private playWalkAnimation() {
  245. if (!this.skeleton) return;
  246. const enemyComp = this.getComponent('EnemyComponent') as any;
  247. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  248. const walkName = anims.walk ?? 'walk';
  249. const idleName = anims.idle ?? 'idle';
  250. if (this.skeleton.findAnimation(walkName)) {
  251. this.skeleton.setAnimation(0, walkName, true);
  252. } else if (this.skeleton.findAnimation(idleName)) {
  253. this.skeleton.setAnimation(0, idleName, true);
  254. }
  255. }
  256. // 播放攻击动画
  257. private playAttackAnimation() {
  258. if (!this.skeleton) return;
  259. const enemyComp2 = this.getComponent('EnemyComponent') as any;
  260. const anims2 = enemyComp2?.getAnimations ? enemyComp2.getAnimations() : {};
  261. const attackName = anims2.attack ?? 'attack';
  262. // 移除频繁打印
  263. if (this.skeleton.findAnimation(attackName)) {
  264. this.skeleton.setAnimation(0, attackName, true);
  265. }
  266. }
  267. private playDeathAnimationAndDestroy() {
  268. console.log(`[EnemyInstance] 开始播放死亡动画并销毁`);
  269. if (this.skeleton) {
  270. const enemyComp = this.getComponent('EnemyComponent') as any;
  271. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  272. const deathName = anims.dead ?? 'dead';
  273. if (this.skeleton.findAnimation(deathName)) {
  274. console.log(`[EnemyInstance] 播放死亡动画: ${deathName}`);
  275. this.skeleton.setAnimation(0, deathName, false);
  276. // 销毁节点在动画完毕后
  277. this.skeleton.setCompleteListener(() => {
  278. console.log(`[EnemyInstance] 死亡动画完成,销毁节点`);
  279. this.node.destroy();
  280. });
  281. return;
  282. }
  283. }
  284. // 若无动画直接销毁
  285. console.log(`[EnemyInstance] 无死亡动画,直接销毁节点`);
  286. this.node.destroy();
  287. }
  288. private spawnCoin() {
  289. const ctrl = this.controller as any; // EnemyController
  290. if (!ctrl?.coinPrefab) return;
  291. const coin = instantiate(ctrl.coinPrefab);
  292. find('Canvas')!.addChild(coin); // 放到 UI 层
  293. const pos = new Vec3();
  294. this.node.getWorldPosition(pos); // 取死亡敌人的世界坐标
  295. coin.worldPosition = pos; // 金币就在敌人身上出现
  296. }
  297. }