EnemyInstance.ts 19 KB

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