EnemyInstance.ts 10 KB

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