EnemyInstance.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. // 检查控制器是否处于清理状态,避免在清理过程中触发游戏事件
  153. const isClearing = (this.controller as any).isClearing;
  154. if (isClearing) {
  155. console.log(`[EnemyInstance] 控制器处于清理状态,跳过死亡通知`);
  156. return;
  157. }
  158. console.log(`[EnemyInstance] 调用 notifyEnemyDead`);
  159. (this.controller as any).notifyEnemyDead(this.node);
  160. } else {
  161. console.warn(`[EnemyInstance] 无法调用 notifyEnemyDead: controller=${!!this.controller}`);
  162. }
  163. }
  164. update(deltaTime: number) {
  165. if (this.state === EnemyState.MOVING) {
  166. this.updateMovement(deltaTime);
  167. } else if (this.state === EnemyState.ATTACKING) {
  168. this.updateAttack(deltaTime);
  169. }
  170. // 不再每帧播放攻击动画,避免日志刷屏
  171. }
  172. // 更新移动逻辑
  173. private updateMovement(deltaTime: number) {
  174. // 检查是否接近游戏区域边界
  175. if (this.checkNearGameArea()) {
  176. this.state = EnemyState.ATTACKING;
  177. this.attackTimer = 0;
  178. this.playAttackAnimation();
  179. return;
  180. }
  181. // 继续移动
  182. this.moveTowardsTarget(deltaTime);
  183. }
  184. // 检查是否接近游戏区域
  185. private checkNearGameArea(): boolean {
  186. const currentPos = this.node.worldPosition;
  187. // 获取游戏区域边界
  188. const gameArea = find('Canvas/GameLevelUI/GameArea');
  189. if (!gameArea) return false;
  190. const uiTransform = gameArea.getComponent(UITransform);
  191. if (!uiTransform) return false;
  192. const gameAreaPos = gameArea.worldPosition;
  193. const halfWidth = uiTransform.width / 2;
  194. const halfHeight = uiTransform.height / 2;
  195. const bounds = {
  196. left: gameAreaPos.x - halfWidth,
  197. right: gameAreaPos.x + halfWidth,
  198. top: gameAreaPos.y + halfHeight,
  199. bottom: gameAreaPos.y - halfHeight
  200. };
  201. // 检查是否在游戏区域内或非常接近
  202. const safeDistance = 50; // 安全距离
  203. const isInside = currentPos.x >= bounds.left - safeDistance &&
  204. currentPos.x <= bounds.right + safeDistance &&
  205. currentPos.y >= bounds.bottom - safeDistance &&
  206. currentPos.y <= bounds.top + safeDistance;
  207. if (isInside) {
  208. return true;
  209. }
  210. return false;
  211. }
  212. // 移动到目标位置
  213. private moveTowardsTarget(deltaTime: number) {
  214. // 使用世界坐标进行移动计算,确保不受父节点坐标系影响
  215. const currentWorldPos = this.node.worldPosition.clone();
  216. // 目标世界坐标:优先使用指定的 Fence,其次退化到游戏区域中心
  217. let targetWorldPos: Vec3;
  218. if (this.targetFence && this.targetFence.isValid) {
  219. targetWorldPos = this.targetFence.worldPosition.clone();
  220. } else {
  221. targetWorldPos = this.gameAreaCenter.clone();
  222. }
  223. const dir = targetWorldPos.subtract(currentWorldPos);
  224. if (dir.length() === 0) return;
  225. dir.normalize();
  226. const moveDistance = this.speed * deltaTime;
  227. const newWorldPos = currentWorldPos.add(dir.multiplyScalar(moveDistance));
  228. // 直接设置世界坐标
  229. this.node.setWorldPosition(newWorldPos);
  230. }
  231. // 更新攻击逻辑
  232. private updateAttack(deltaTime: number) {
  233. this.attackTimer -= deltaTime;
  234. if (this.attackTimer <= 0) {
  235. // 执行攻击
  236. this.performAttack();
  237. // 重置攻击计时器
  238. this.attackTimer = this.attackInterval;
  239. }
  240. }
  241. // 执行攻击
  242. private performAttack() {
  243. if (!this.controller) {
  244. return;
  245. }
  246. // 对墙体造成伤害
  247. this.controller.damageWall(this.attackPower);
  248. }
  249. // 播放行走动画
  250. private playWalkAnimation() {
  251. if (!this.skeleton) return;
  252. const enemyComp = this.getComponent('EnemyComponent') as any;
  253. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  254. const walkName = anims.walk ?? 'walk';
  255. const idleName = anims.idle ?? 'idle';
  256. if (this.skeleton.findAnimation(walkName)) {
  257. this.skeleton.setAnimation(0, walkName, true);
  258. } else if (this.skeleton.findAnimation(idleName)) {
  259. this.skeleton.setAnimation(0, idleName, true);
  260. }
  261. }
  262. // 播放攻击动画
  263. private playAttackAnimation() {
  264. if (!this.skeleton) return;
  265. const enemyComp2 = this.getComponent('EnemyComponent') as any;
  266. const anims2 = enemyComp2?.getAnimations ? enemyComp2.getAnimations() : {};
  267. const attackName = anims2.attack ?? 'attack';
  268. // 移除频繁打印
  269. if (this.skeleton.findAnimation(attackName)) {
  270. this.skeleton.setAnimation(0, attackName, true);
  271. }
  272. }
  273. private playDeathAnimationAndDestroy() {
  274. console.log(`[EnemyInstance] 开始播放死亡动画并销毁`);
  275. if (this.skeleton) {
  276. const enemyComp = this.getComponent('EnemyComponent') as any;
  277. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  278. const deathName = anims.dead ?? 'dead';
  279. if (this.skeleton.findAnimation(deathName)) {
  280. console.log(`[EnemyInstance] 播放死亡动画: ${deathName}`);
  281. this.skeleton.setAnimation(0, deathName, false);
  282. // 销毁节点在动画完毕后
  283. this.skeleton.setCompleteListener(() => {
  284. console.log(`[EnemyInstance] 死亡动画完成,销毁节点`);
  285. this.node.destroy();
  286. });
  287. return;
  288. }
  289. }
  290. // 若无动画直接销毁
  291. console.log(`[EnemyInstance] 无死亡动画,直接销毁节点`);
  292. this.node.destroy();
  293. }
  294. private spawnCoin() {
  295. const ctrl = this.controller as any; // EnemyController
  296. if (!ctrl?.coinPrefab) return;
  297. const coin = instantiate(ctrl.coinPrefab);
  298. find('Canvas')!.addChild(coin); // 放到 UI 层
  299. const pos = new Vec3();
  300. this.node.getWorldPosition(pos); // 取死亡敌人的世界坐标
  301. coin.worldPosition = pos; // 金币就在敌人身上出现
  302. }
  303. }