EnemyInstance.ts 11 KB

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