EnemyInstance.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. import { _decorator, Component, Node, ProgressBar, Label, Vec3, find, UITransform, Collider2D, Contact2DType, IPhysics2DContact } 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. public movingDirection: number = 1; // 1: 向右, -1: 向左
  30. public targetY: number = 0; // 目标Y位置
  31. public changeDirectionTime: number = 0; // 下次改变方向的时间
  32. // 攻击属性
  33. public attackInterval: number = 2; // 攻击间隔(秒)
  34. private attackTimer: number = 0;
  35. // 对控制器的引用
  36. public controller: EnemyControllerType = null;
  37. // 敌人当前状态
  38. private state: EnemyState = EnemyState.MOVING;
  39. // 游戏区域中心
  40. private gameAreaCenter: Vec3 = new Vec3();
  41. // 碰撞的墙体
  42. private collidedWall: Node = null;
  43. // 骨骼动画组件
  44. private skeleton: sp.Skeleton | null = null;
  45. // 调试标记,避免重复输出日志
  46. private _debugFlag: boolean = false;
  47. start() {
  48. // 初始化敌人
  49. this.initializeEnemy();
  50. }
  51. // 初始化敌人
  52. private initializeEnemy() {
  53. this.health = this.maxHealth;
  54. this.state = EnemyState.MOVING;
  55. if (this.speed === 0) this.speed = 50;
  56. if (this.attackPower === 0) this.attackPower = 10;
  57. this.attackInterval = 2.0; // 默认攻击间隔
  58. this.attackTimer = 0;
  59. // 获取骨骼动画组件
  60. this.skeleton = this.getComponent(sp.Skeleton);
  61. this.playWalkAnimation();
  62. // 计算游戏区域中心
  63. this.calculateGameAreaCenter();
  64. // 初始化碰撞检测
  65. this.setupCollider();
  66. }
  67. // 设置碰撞器
  68. setupCollider() {
  69. // 检查节点是否有碰撞器
  70. let collider = this.node.getComponent(Collider2D);
  71. if (!collider) {
  72. return;
  73. }
  74. // 设置碰撞事件监听
  75. collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  76. }
  77. // 碰撞开始事件
  78. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  79. const nodeName = otherCollider.node.name;
  80. // 如果碰到墙体,停止移动并开始攻击
  81. if (nodeName.includes('Wall') || nodeName.includes('wall') || nodeName.includes('Fence') || nodeName.includes('Jiguang')) {
  82. this.state = EnemyState.ATTACKING;
  83. this.attackTimer = 0; // 立即开始攻击
  84. // 切换攻击动画
  85. this.playAttackAnimation();
  86. }
  87. }
  88. // 获取节点路径
  89. getNodePath(node: Node): string {
  90. let path = node.name;
  91. let current = node;
  92. while (current.parent) {
  93. current = current.parent;
  94. path = current.name + '/' + path;
  95. }
  96. return path;
  97. }
  98. // 计算游戏区域中心
  99. private calculateGameAreaCenter() {
  100. const gameArea = find('Canvas/GameLevelUI/GameArea');
  101. if (gameArea) {
  102. this.gameAreaCenter = gameArea.worldPosition;
  103. }
  104. }
  105. // 更新血量显示
  106. updateHealthDisplay() {
  107. // 更新血条
  108. const hpBar = this.node.getChildByName('HPBar');
  109. if (hpBar) {
  110. const progressBar = hpBar.getComponent(ProgressBar);
  111. if (progressBar) {
  112. progressBar.progress = this.health / this.maxHealth;
  113. }
  114. }
  115. // 更新血量数字
  116. const hpLabel = this.node.getChildByName('HPLabel');
  117. if (hpLabel) {
  118. const label = hpLabel.getComponent(Label);
  119. if (label) {
  120. label.string = this.health.toString();
  121. }
  122. }
  123. }
  124. // 受到伤害
  125. takeDamage(damage: number) {
  126. this.health -= damage;
  127. // 更新血量显示
  128. this.updateHealthDisplay();
  129. // 如果血量低于等于0,销毁敌人
  130. if (this.health <= 0 && this.state !== EnemyState.DEAD) {
  131. this.state = EnemyState.DEAD;
  132. // 进入死亡流程,禁用碰撞避免重复命中
  133. const col = this.getComponent(Collider2D);
  134. if (col) col.enabled = false;
  135. this.playDeathAnimationAndDestroy();
  136. }
  137. }
  138. onDestroy() {
  139. // 通知控制器 & GameManager
  140. if (this.controller && typeof (this.controller as any).notifyEnemyDead === 'function') {
  141. (this.controller as any).notifyEnemyDead(this.node);
  142. }
  143. }
  144. update(deltaTime: number) {
  145. if (this.state === EnemyState.MOVING) {
  146. this.updateMovement(deltaTime);
  147. } else if (this.state === EnemyState.ATTACKING) {
  148. this.updateAttack(deltaTime);
  149. }
  150. // 不再每帧播放攻击动画,避免日志刷屏
  151. }
  152. // 更新移动逻辑
  153. private updateMovement(deltaTime: number) {
  154. // 检查是否接近游戏区域边界
  155. if (this.checkNearGameArea()) {
  156. this.state = EnemyState.ATTACKING;
  157. this.attackTimer = 0;
  158. this.playAttackAnimation();
  159. return;
  160. }
  161. // 继续移动
  162. this.moveTowardsTarget(deltaTime);
  163. }
  164. // 检查是否接近游戏区域
  165. private checkNearGameArea(): boolean {
  166. const currentPos = this.node.worldPosition;
  167. // 获取游戏区域边界
  168. const gameArea = find('Canvas/GameLevelUI/GameArea');
  169. if (!gameArea) return false;
  170. const uiTransform = gameArea.getComponent(UITransform);
  171. if (!uiTransform) return false;
  172. const gameAreaPos = gameArea.worldPosition;
  173. const halfWidth = uiTransform.width / 2;
  174. const halfHeight = uiTransform.height / 2;
  175. const bounds = {
  176. left: gameAreaPos.x - halfWidth,
  177. right: gameAreaPos.x + halfWidth,
  178. top: gameAreaPos.y + halfHeight,
  179. bottom: gameAreaPos.y - halfHeight
  180. };
  181. // 检查是否在游戏区域内或非常接近
  182. const safeDistance = 50; // 安全距离
  183. const isInside = currentPos.x >= bounds.left - safeDistance &&
  184. currentPos.x <= bounds.right + safeDistance &&
  185. currentPos.y >= bounds.bottom - safeDistance &&
  186. currentPos.y <= bounds.top + safeDistance;
  187. if (isInside) {
  188. return true;
  189. }
  190. return false;
  191. }
  192. // 移动到目标位置
  193. private moveTowardsTarget(deltaTime: number) {
  194. const currentPos = this.node.position;
  195. // 简单的向中心移动
  196. const targetPos = new Vec3(0, 0, 0); // 移动到中心
  197. const direction = targetPos.subtract(currentPos).normalize();
  198. // 应用移动
  199. const moveDistance = this.speed * deltaTime;
  200. const newPos = currentPos.add(direction.multiplyScalar(moveDistance));
  201. this.node.position = newPos;
  202. }
  203. // 更新攻击逻辑
  204. private updateAttack(deltaTime: number) {
  205. this.attackTimer -= deltaTime;
  206. if (this.attackTimer <= 0) {
  207. // 执行攻击
  208. this.performAttack();
  209. // 重置攻击计时器
  210. this.attackTimer = this.attackInterval;
  211. }
  212. }
  213. // 执行攻击
  214. private performAttack() {
  215. if (!this.controller) {
  216. return;
  217. }
  218. // 对墙体造成伤害
  219. this.controller.damageWall(this.attackPower);
  220. }
  221. // 播放行走动画
  222. private playWalkAnimation() {
  223. if (!this.skeleton) return;
  224. const enemyComp = this.getComponent('EnemyComponent') as any;
  225. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  226. const walkName = anims.walk ?? 'walk';
  227. const idleName = anims.idle ?? 'idle';
  228. if (this.skeleton.findAnimation(walkName)) {
  229. this.skeleton.setAnimation(0, walkName, true);
  230. } else if (this.skeleton.findAnimation(idleName)) {
  231. this.skeleton.setAnimation(0, idleName, true);
  232. }
  233. }
  234. // 播放攻击动画
  235. private playAttackAnimation() {
  236. if (!this.skeleton) return;
  237. const enemyComp2 = this.getComponent('EnemyComponent') as any;
  238. const anims2 = enemyComp2?.getAnimations ? enemyComp2.getAnimations() : {};
  239. const attackName = anims2.attack ?? 'attack';
  240. // 移除频繁打印
  241. if (this.skeleton.findAnimation(attackName)) {
  242. this.skeleton.setAnimation(0, attackName, true);
  243. }
  244. }
  245. private playDeathAnimationAndDestroy() {
  246. if (this.skeleton) {
  247. const enemyComp = this.getComponent('EnemyComponent') as any;
  248. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  249. const deathName = anims.dead ?? 'dead';
  250. if (this.skeleton.findAnimation(deathName)) {
  251. this.skeleton.setAnimation(0, deathName, false);
  252. // 销毁节点在动画完毕后
  253. this.skeleton.setCompleteListener(() => {
  254. this.node.destroy();
  255. });
  256. return;
  257. }
  258. }
  259. // 若无动画直接销毁
  260. this.node.destroy();
  261. }
  262. }