EnemyInstance.ts 15 KB

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