EnemyInstance.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. import { _decorator, Component, Node, ProgressBar, Label, Vec3, find, UITransform, Collider2D, Contact2DType, IPhysics2DContact, instantiate, resources, Prefab, JsonAsset } from 'cc';
  2. import { sp } from 'cc';
  3. import { DamageNumberAni } from '../Animations/DamageNumberAni';
  4. import { HPBarAnimation } from '../Animations/HPBarAnimation';
  5. import { EnemyComponent } from './EnemyComponent';
  6. const { ccclass, property } = _decorator;
  7. // 前向声明EnemyController接口,避免循环引用
  8. interface EnemyControllerType {
  9. gameBounds: {
  10. left: number;
  11. right: number;
  12. top: number;
  13. bottom: number;
  14. };
  15. damageWall: (damage: number) => void;
  16. getComponent: (componentType: any) => any;
  17. }
  18. // 敌人状态枚举
  19. enum EnemyState {
  20. MOVING, // 移动中
  21. ATTACKING, // 攻击中
  22. DEAD // 死亡
  23. }
  24. // 单个敌人实例的组件
  25. @ccclass('EnemyInstance')
  26. export class EnemyInstance extends Component {
  27. // 敌人属性(从配置文件读取)
  28. public health: number = 0;
  29. public maxHealth: number = 0;
  30. public speed: number = 0;
  31. public attackPower: number = 0;
  32. // 敌人配置ID
  33. public enemyId: string = '';
  34. // 敌人配置数据
  35. private enemyConfig: any = null;
  36. // 敌人配置数据库
  37. private static enemyDatabase: any = null;
  38. // === 新增属性 ===
  39. /** 是否从上方生成 */
  40. public spawnFromTop: boolean = true;
  41. /** 目标 Fence 节点(TopFence / BottomFence) */
  42. public targetFence: Node | null = null;
  43. // 移动属性
  44. public movingDirection: number = 1; // 1: 向右, -1: 向左
  45. public targetY: number = 0; // 目标Y位置
  46. public changeDirectionTime: number = 0; // 下次改变方向的时间
  47. // 攻击属性
  48. public attackInterval: number = 0; // 攻击间隔(秒),从配置文件读取
  49. private attackTimer: number = 0;
  50. // 对控制器的引用
  51. public controller: EnemyControllerType = null;
  52. // 敌人当前状态
  53. private state: EnemyState = EnemyState.MOVING;
  54. // 游戏区域中心
  55. private gameAreaCenter: Vec3 = new Vec3();
  56. // 碰撞的墙体
  57. private collidedWall: Node = null;
  58. // 骨骼动画组件
  59. private skeleton: sp.Skeleton | null = null;
  60. // 血条动画组件
  61. private hpBarAnimation: HPBarAnimation | null = null;
  62. // 暂停状态标记
  63. private isPaused: boolean = false;
  64. start() {
  65. // 初始化敌人
  66. this.initializeEnemy();
  67. }
  68. // 静态方法:加载敌人配置数据库
  69. public static async loadEnemyDatabase(): Promise<void> {
  70. if (EnemyInstance.enemyDatabase) return;
  71. return new Promise((resolve, reject) => {
  72. resources.load('data/enemies', JsonAsset, (err, jsonAsset) => {
  73. if (err) {
  74. console.error('[EnemyInstance] 加载敌人配置失败:', err);
  75. reject(err);
  76. return;
  77. }
  78. EnemyInstance.enemyDatabase = jsonAsset.json;
  79. console.log('[EnemyInstance] 敌人配置数据库加载成功');
  80. resolve();
  81. });
  82. });
  83. }
  84. // 设置敌人配置
  85. public setEnemyConfig(enemyId: string): void {
  86. this.enemyId = enemyId;
  87. if (!EnemyInstance.enemyDatabase) {
  88. console.error('[EnemyInstance] 敌人配置数据库未加载');
  89. return;
  90. }
  91. // 从数据库中查找敌人配置
  92. const enemies = EnemyInstance.enemyDatabase.enemies;
  93. this.enemyConfig = enemies.find((enemy: any) => enemy.id === enemyId);
  94. if (!this.enemyConfig) {
  95. console.error(`[EnemyInstance] 未找到敌人配置: ${enemyId}`);
  96. return;
  97. }
  98. // 应用配置到敌人属性
  99. this.applyEnemyConfig();
  100. }
  101. // 应用敌人配置到属性
  102. private applyEnemyConfig(): void {
  103. if (!this.enemyConfig) return;
  104. // 从stats节点读取基础属性
  105. const stats = this.enemyConfig.stats || {};
  106. this.health = stats.health || 30;
  107. this.maxHealth = stats.maxHealth || this.health;
  108. // 从movement节点读取移动速度
  109. const movement = this.enemyConfig.movement || {};
  110. this.speed = movement.speed || 50;
  111. // 从combat节点读取攻击力
  112. const combat = this.enemyConfig.combat || {};
  113. this.attackPower = combat.attackDamage || 10;
  114. // 设置攻击间隔
  115. this.attackInterval = combat.attackCooldown || 2.0;
  116. console.log(`[EnemyInstance] 应用敌人配置: ${this.enemyConfig.name}, 血量: ${this.health}/${this.maxHealth}, 速度: ${this.speed}, 攻击力: ${this.attackPower}, 攻击间隔: ${this.attackInterval}`);
  117. }
  118. // 获取敌人配置信息
  119. public getEnemyConfig(): any {
  120. return this.enemyConfig;
  121. }
  122. // 获取敌人名称
  123. public getEnemyName(): string {
  124. return this.enemyConfig?.name || '未知敌人';
  125. }
  126. // 获取敌人类型
  127. public getEnemyType(): string {
  128. return this.enemyConfig?.type || 'basic';
  129. }
  130. // 获取敌人稀有度
  131. public getEnemyRarity(): string {
  132. return this.enemyConfig?.rarity || 'common';
  133. }
  134. // 获取金币奖励
  135. public getGoldReward(): number {
  136. return this.enemyConfig?.goldReward || 1;
  137. }
  138. // 初始化敌人
  139. private initializeEnemy() {
  140. // 确保血量正确设置
  141. if (this.maxHealth > 0) {
  142. this.health = this.maxHealth;
  143. }
  144. this.state = EnemyState.MOVING;
  145. // 只有在攻击间隔未设置时才使用默认值
  146. if (this.attackInterval <= 0) {
  147. this.attackInterval = 2.0; // 默认攻击间隔
  148. }
  149. this.attackTimer = 0;
  150. // 初始化血条动画组件
  151. this.initializeHPBarAnimation();
  152. // 获取骨骼动画组件
  153. this.skeleton = this.getComponent(sp.Skeleton);
  154. this.playWalkAnimation();
  155. // 计算游戏区域中心
  156. this.calculateGameAreaCenter();
  157. // 初始化碰撞检测
  158. this.setupCollider();
  159. }
  160. // 设置碰撞器
  161. setupCollider() {
  162. // 检查节点是否有碰撞器
  163. let collider = this.node.getComponent(Collider2D);
  164. if (!collider) {
  165. return;
  166. }
  167. // 设置碰撞事件监听
  168. collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  169. }
  170. // 碰撞开始事件
  171. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  172. const nodeName = otherCollider.node.name;
  173. // 如果碰到墙体,停止移动并开始攻击
  174. if (nodeName.includes('Wall') || nodeName.includes('wall') || nodeName.includes('Fence') || nodeName.includes('Jiguang')) {
  175. this.state = EnemyState.ATTACKING;
  176. this.attackTimer = 0; // 立即开始攻击
  177. // 切换攻击动画
  178. this.playAttackAnimation();
  179. }
  180. }
  181. // 获取节点路径
  182. getNodePath(node: Node): string {
  183. let path = node.name;
  184. let current = node;
  185. while (current.parent) {
  186. current = current.parent;
  187. path = current.name + '/' + path;
  188. }
  189. return path;
  190. }
  191. // 计算游戏区域中心
  192. private calculateGameAreaCenter() {
  193. const gameArea = find('Canvas/GameLevelUI/GameArea');
  194. if (gameArea) {
  195. this.gameAreaCenter = gameArea.worldPosition;
  196. }
  197. }
  198. /**
  199. * 初始化血条动画组件
  200. */
  201. private initializeHPBarAnimation() {
  202. const hpBar = this.node.getChildByName('HPBar');
  203. if (hpBar) {
  204. // 查找红色和黄色血条节点
  205. const redBarNode = hpBar.getChildByName('RedBar');
  206. const yellowBarNode = hpBar.getChildByName('YellowBar');
  207. if (redBarNode && yellowBarNode) {
  208. // 添加血条动画组件
  209. this.hpBarAnimation = this.node.addComponent(HPBarAnimation);
  210. if (this.hpBarAnimation) {
  211. // 正确设置红色和黄色血条节点引用
  212. this.hpBarAnimation.redBarNode = redBarNode;
  213. this.hpBarAnimation.yellowBarNode = yellowBarNode;
  214. console.log(`[EnemyInstance] 血条动画组件已初始化`);
  215. }
  216. } else {
  217. console.warn(`[EnemyInstance] HPBar下未找到RedBar或YellowBar节点,RedBar: ${!!redBarNode}, YellowBar: ${!!yellowBarNode}`);
  218. }
  219. } else {
  220. console.warn(`[EnemyInstance] 未找到HPBar节点,无法初始化血条动画`);
  221. }
  222. }
  223. // 更新血量显示
  224. updateHealthDisplay() {
  225. // 确保血量值在有效范围内
  226. this.health = Math.max(0, Math.min(this.maxHealth, this.health));
  227. const healthProgress = this.maxHealth > 0 ? this.health / this.maxHealth : 0;
  228. console.log(`[EnemyInstance] 更新血量显示: ${this.health}/${this.maxHealth} (${(healthProgress * 100).toFixed(1)}%)`);
  229. // 使用血条动画组件更新血条
  230. if (this.hpBarAnimation) {
  231. this.hpBarAnimation.updateProgress(healthProgress);
  232. } else {
  233. // 备用方案:直接更新血条
  234. const hpBar = this.node.getChildByName('HPBar');
  235. if (hpBar) {
  236. const progressBar = hpBar.getComponent(ProgressBar);
  237. if (progressBar) {
  238. progressBar.progress = healthProgress;
  239. }
  240. }
  241. }
  242. // 更新血量数字
  243. const hpLabel = this.node.getChildByName('HPLabel');
  244. if (hpLabel) {
  245. const label = hpLabel.getComponent(Label);
  246. if (label) {
  247. // 显示整数血量值
  248. label.string = Math.ceil(this.health).toString();
  249. }
  250. }
  251. }
  252. // 受到伤害
  253. takeDamage(damage: number, isCritical: boolean = false) {
  254. // 如果已经死亡,不再处理伤害
  255. if (this.state === EnemyState.DEAD) {
  256. return;
  257. }
  258. // 确保伤害值为正数
  259. if (damage <= 0) {
  260. console.warn(`[EnemyInstance] 无效的伤害值: ${damage}`);
  261. return;
  262. }
  263. // 计算新的血量,确保不会低于0
  264. const newHealth = Math.max(0, this.health - damage);
  265. const actualDamage = this.health - newHealth;
  266. this.health = newHealth;
  267. console.log(`[EnemyInstance] 敌人受到伤害: ${actualDamage}, 剩余血量: ${this.health}/${this.maxHealth}`);
  268. // 显示伤害数字动画(在敌人头顶)
  269. // 优先使用EnemyController节点上的DamageNumberAni组件实例
  270. if (this.controller) {
  271. const damageAni = this.controller.getComponent(DamageNumberAni);
  272. if (damageAni) {
  273. damageAni.showDamageNumber(actualDamage, this.node.worldPosition, isCritical);
  274. } else {
  275. // 如果没有找到组件实例,使用静态方法作为备用
  276. DamageNumberAni.showDamageNumber(actualDamage, this.node.worldPosition, isCritical);
  277. }
  278. } else {
  279. // 如果没有controller引用,使用静态方法
  280. DamageNumberAni.showDamageNumber(actualDamage, this.node.worldPosition, isCritical);
  281. }
  282. // 更新血量显示和动画
  283. this.updateHealthDisplay();
  284. // 如果血量低于等于0,销毁敌人
  285. if (this.health <= 0) {
  286. console.log(`[EnemyInstance] 敌人死亡,开始销毁流程`);
  287. this.state = EnemyState.DEAD;
  288. this.spawnCoin();
  289. // 进入死亡流程,禁用碰撞避免重复命中
  290. const col = this.getComponent(Collider2D);
  291. if (col) col.enabled = false;
  292. this.playDeathAnimationAndDestroy();
  293. }
  294. }
  295. onDestroy() {
  296. console.log(`[EnemyInstance] onDestroy 被调用,准备通知控制器`);
  297. // 通知控制器 & GameManager
  298. if (this.controller && typeof (this.controller as any).notifyEnemyDead === 'function') {
  299. // 检查控制器是否处于清理状态,避免在清理过程中触发游戏事件
  300. const isClearing = (this.controller as any).isClearing;
  301. if (isClearing) {
  302. console.log(`[EnemyInstance] 控制器处于清理状态,跳过死亡通知`);
  303. return;
  304. }
  305. console.log(`[EnemyInstance] 调用 notifyEnemyDead`);
  306. (this.controller as any).notifyEnemyDead(this.node);
  307. } else {
  308. console.warn(`[EnemyInstance] 无法调用 notifyEnemyDead: controller=${!!this.controller}`);
  309. }
  310. }
  311. update(deltaTime: number) {
  312. // 如果敌人被暂停,则不执行任何更新逻辑
  313. if (this.isPaused) {
  314. return;
  315. }
  316. if (this.state === EnemyState.MOVING) {
  317. this.updateMovement(deltaTime);
  318. } else if (this.state === EnemyState.ATTACKING) {
  319. this.updateAttack(deltaTime);
  320. }
  321. // 不再每帧播放攻击动画,避免日志刷屏
  322. }
  323. // 更新移动逻辑
  324. private updateMovement(deltaTime: number) {
  325. // 检查是否接近游戏区域边界
  326. if (this.checkNearGameArea()) {
  327. this.state = EnemyState.ATTACKING;
  328. this.attackTimer = 0;
  329. this.playAttackAnimation();
  330. return;
  331. }
  332. // 继续移动
  333. this.moveTowardsTarget(deltaTime);
  334. }
  335. // 检查是否接近游戏区域
  336. private checkNearGameArea(): boolean {
  337. const currentPos = this.node.worldPosition;
  338. // 获取游戏区域边界
  339. const gameArea = find('Canvas/GameLevelUI/GameArea');
  340. if (!gameArea) return false;
  341. const uiTransform = gameArea.getComponent(UITransform);
  342. if (!uiTransform) return false;
  343. const gameAreaPos = gameArea.worldPosition;
  344. const halfWidth = uiTransform.width / 2;
  345. const halfHeight = uiTransform.height / 2;
  346. const bounds = {
  347. left: gameAreaPos.x - halfWidth,
  348. right: gameAreaPos.x + halfWidth,
  349. top: gameAreaPos.y + halfHeight,
  350. bottom: gameAreaPos.y - halfHeight
  351. };
  352. // 检查是否在游戏区域内或非常接近
  353. const safeDistance = 50; // 安全距离
  354. const isInside = currentPos.x >= bounds.left - safeDistance &&
  355. currentPos.x <= bounds.right + safeDistance &&
  356. currentPos.y >= bounds.bottom - safeDistance &&
  357. currentPos.y <= bounds.top + safeDistance;
  358. if (isInside) {
  359. return true;
  360. }
  361. return false;
  362. }
  363. // 移动到目标位置
  364. private moveTowardsTarget(deltaTime: number) {
  365. // 使用世界坐标进行移动计算,确保不受父节点坐标系影响
  366. const currentWorldPos = this.node.worldPosition.clone();
  367. // 目标世界坐标:优先使用指定的 Fence,其次退化到游戏区域中心
  368. let targetWorldPos: Vec3;
  369. if (this.targetFence && this.targetFence.isValid) {
  370. targetWorldPos = this.targetFence.worldPosition.clone();
  371. } else {
  372. targetWorldPos = this.gameAreaCenter.clone();
  373. }
  374. const dir = targetWorldPos.subtract(currentWorldPos);
  375. if (dir.length() === 0) return;
  376. dir.normalize();
  377. const moveDistance = this.speed * deltaTime;
  378. const newWorldPos = currentWorldPos.add(dir.multiplyScalar(moveDistance));
  379. // 直接设置世界坐标
  380. this.node.setWorldPosition(newWorldPos);
  381. }
  382. // 更新攻击逻辑
  383. private updateAttack(deltaTime: number) {
  384. this.attackTimer -= deltaTime;
  385. if (this.attackTimer <= 0) {
  386. // 执行攻击
  387. this.performAttack();
  388. // 重置攻击计时器
  389. this.attackTimer = this.attackInterval;
  390. }
  391. }
  392. // 执行攻击
  393. private performAttack() {
  394. if (!this.controller) {
  395. return;
  396. }
  397. // 对墙体造成伤害
  398. this.controller.damageWall(this.attackPower);
  399. }
  400. // 播放行走动画
  401. private playWalkAnimation() {
  402. if (!this.skeleton) return;
  403. const enemyComp = this.getComponent('EnemyComponent') as any;
  404. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  405. const walkName = anims.walk ?? 'walk';
  406. const idleName = anims.idle ?? 'idle';
  407. if (this.skeleton.findAnimation(walkName)) {
  408. this.skeleton.setAnimation(0, walkName, true);
  409. } else if (this.skeleton.findAnimation(idleName)) {
  410. this.skeleton.setAnimation(0, idleName, true);
  411. }
  412. }
  413. // 播放攻击动画
  414. private playAttackAnimation() {
  415. if (!this.skeleton) return;
  416. const enemyComp2 = this.getComponent('EnemyComponent') as any;
  417. const anims2 = enemyComp2?.getAnimations ? enemyComp2.getAnimations() : {};
  418. const attackName = anims2.attack ?? 'attack';
  419. // 移除频繁打印
  420. if (this.skeleton.findAnimation(attackName)) {
  421. this.skeleton.setAnimation(0, attackName, true);
  422. }
  423. }
  424. private playDeathAnimationAndDestroy() {
  425. console.log(`[EnemyInstance] 开始播放死亡动画并销毁`);
  426. if (this.skeleton) {
  427. const enemyComp = this.getComponent('EnemyComponent') as any;
  428. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  429. const deathName = anims.dead ?? 'dead';
  430. if (this.skeleton.findAnimation(deathName)) {
  431. console.log(`[EnemyInstance] 播放死亡动画: ${deathName}`);
  432. this.skeleton.setAnimation(0, deathName, false);
  433. // 销毁节点在动画完毕后
  434. this.skeleton.setCompleteListener(() => {
  435. console.log(`[EnemyInstance] 死亡动画完成,销毁节点`);
  436. this.node.destroy();
  437. });
  438. return;
  439. }
  440. }
  441. // 若无动画直接销毁
  442. console.log(`[EnemyInstance] 无死亡动画,直接销毁节点`);
  443. this.node.destroy();
  444. }
  445. private spawnCoin() {
  446. const ctrl = this.controller as any; // EnemyController
  447. if (!ctrl?.coinPrefab) return;
  448. const coin = instantiate(ctrl.coinPrefab);
  449. find('Canvas')!.addChild(coin); // 放到 UI 层
  450. const pos = new Vec3();
  451. this.node.getWorldPosition(pos); // 取死亡敌人的世界坐标
  452. coin.worldPosition = pos; // 金币就在敌人身上出现
  453. }
  454. /**
  455. * 暂停敌人
  456. */
  457. public pause(): void {
  458. this.isPaused = true;
  459. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 已暂停`);
  460. }
  461. /**
  462. * 恢复敌人
  463. */
  464. public resume(): void {
  465. this.isPaused = false;
  466. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 已恢复`);
  467. }
  468. /**
  469. * 检查是否暂停
  470. */
  471. public isPausedState(): boolean {
  472. return this.isPaused;
  473. }
  474. }