EnemyInstance.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. import { _decorator, Component, Node, ProgressBar, Label, Vec3, find, UITransform, Collider2D, Contact2DType, IPhysics2DContact, instantiate, resources, Prefab, JsonAsset, RigidBody2D, ERigidBody2DType } 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. import { EnemyAudio } from '../AudioManager/EnemyAudios';
  7. const { ccclass, property } = _decorator;
  8. // 前向声明EnemyController接口,避免循环引用
  9. interface EnemyControllerType {
  10. gameBounds: {
  11. left: number;
  12. right: number;
  13. top: number;
  14. bottom: number;
  15. };
  16. damageWall: (damage: number) => void;
  17. getComponent: (componentType: any) => any;
  18. }
  19. // 敌人状态枚举
  20. enum EnemyState {
  21. MOVING, // 移动中
  22. ATTACKING, // 攻击中
  23. DEAD // 死亡
  24. }
  25. // 单个敌人实例的组件
  26. @ccclass('EnemyInstance')
  27. export class EnemyInstance extends Component {
  28. // 敌人属性(从配置文件读取)
  29. public health: number = 0;
  30. public maxHealth: number = 0;
  31. public speed: number = 0;
  32. public attackPower: number = 0;
  33. // 敌人配置ID
  34. public enemyId: string = '';
  35. // 敌人配置数据
  36. private enemyConfig: any = null;
  37. // 敌人配置数据库
  38. private static enemyDatabase: any = null;
  39. // === 新增属性 ===
  40. /** 是否从上方生成 */
  41. public spawnFromTop: boolean = true;
  42. /** 目标 Fence 节点(TopFence / BottomFence) */
  43. public targetFence: Node | null = null;
  44. // 移动属性
  45. public movingDirection: number = 1; // 1: 向右, -1: 向左
  46. public targetY: number = 0; // 目标Y位置
  47. public changeDirectionTime: number = 0; // 下次改变方向的时间
  48. // 攻击属性
  49. public attackInterval: number = 0; // 攻击间隔(秒),从配置文件读取
  50. private attackTimer: number = 0;
  51. // 对控制器的引用
  52. public controller: EnemyControllerType = null;
  53. // 敌人当前状态
  54. private state: EnemyState = EnemyState.MOVING;
  55. // 游戏区域中心
  56. private gameAreaCenter: Vec3 = new Vec3();
  57. // 碰撞的墙体
  58. private collidedWall: Node = null;
  59. // 骨骼动画组件
  60. private skeleton: sp.Skeleton | null = null;
  61. // 血条动画组件
  62. private hpBarAnimation: HPBarAnimation | null = null;
  63. // 暂停状态标记
  64. private isPaused: boolean = false;
  65. start() {
  66. // 初始化敌人
  67. this.initializeEnemy();
  68. }
  69. // 静态方法:加载敌人配置数据库
  70. public static async loadEnemyDatabase(): Promise<void> {
  71. if (EnemyInstance.enemyDatabase) return;
  72. return new Promise((resolve, reject) => {
  73. resources.load('data/enemies', JsonAsset, (err, jsonAsset) => {
  74. if (err) {
  75. console.error('[EnemyInstance] 加载敌人配置失败:', err);
  76. reject(err);
  77. return;
  78. }
  79. EnemyInstance.enemyDatabase = jsonAsset.json;
  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. }
  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. console.warn(`[EnemyInstance] 敌人节点 ${this.node.name} 没有碰撞器组件`);
  166. return;
  167. }
  168. // 确保有RigidBody2D组件,这对于碰撞检测是必需的
  169. let rigidBody = this.node.getComponent(RigidBody2D);
  170. if (!rigidBody) {
  171. console.log(`[EnemyInstance] 为敌人节点 ${this.node.name} 添加RigidBody2D组件`);
  172. rigidBody = this.node.addComponent(RigidBody2D);
  173. }
  174. // 设置刚体属性
  175. if (rigidBody) {
  176. rigidBody.type = ERigidBody2DType.Dynamic; // 动态刚体
  177. rigidBody.enabledContactListener = true; // 启用碰撞监听
  178. rigidBody.gravityScale = 0; // 不受重力影响
  179. rigidBody.linearDamping = 0; // 无线性阻尼
  180. rigidBody.angularDamping = 0; // 无角阻尼
  181. rigidBody.allowSleep = false; // 不允许休眠
  182. rigidBody.fixedRotation = true; // 固定旋转
  183. }
  184. // 设置碰撞事件监听
  185. collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  186. console.log(`[EnemyInstance] 敌人 ${this.node.name} 碰撞器设置完成,碰撞器启用: ${collider.enabled}, 刚体启用: ${rigidBody?.enabled}`);
  187. }
  188. // 碰撞开始事件
  189. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  190. const nodeName = otherCollider.node.name;
  191. // 如果碰到墙体,停止移动并开始攻击
  192. if (nodeName.includes('Wall') || nodeName.includes('wall') || nodeName.includes('Fence') || nodeName.includes('Jiguang')) {
  193. this.state = EnemyState.ATTACKING;
  194. this.attackTimer = 0; // 立即开始攻击
  195. // 切换攻击动画
  196. this.playAttackAnimation();
  197. }
  198. }
  199. // 获取节点路径
  200. getNodePath(node: Node): string {
  201. let path = node.name;
  202. let current = node;
  203. while (current.parent) {
  204. current = current.parent;
  205. path = current.name + '/' + path;
  206. }
  207. return path;
  208. }
  209. // 计算游戏区域中心
  210. private calculateGameAreaCenter() {
  211. const gameArea = find('Canvas/GameLevelUI/GameArea');
  212. if (gameArea) {
  213. this.gameAreaCenter = gameArea.worldPosition;
  214. }
  215. }
  216. /**
  217. * 初始化血条动画组件
  218. */
  219. private initializeHPBarAnimation() {
  220. const hpBar = this.node.getChildByName('HPBar');
  221. if (hpBar) {
  222. // 查找红色和黄色血条节点
  223. const redBarNode = hpBar.getChildByName('RedBar');
  224. const yellowBarNode = hpBar.getChildByName('YellowBar');
  225. if (redBarNode && yellowBarNode) {
  226. // 添加血条动画组件
  227. this.hpBarAnimation = this.node.addComponent(HPBarAnimation);
  228. if (this.hpBarAnimation) {
  229. // 正确设置红色和黄色血条节点引用
  230. this.hpBarAnimation.redBarNode = redBarNode;
  231. this.hpBarAnimation.yellowBarNode = yellowBarNode;
  232. this.hpBarAnimation.hpBarRootNode = hpBar; // 设置HPBar根节点
  233. console.log(`[EnemyInstance] 血条动画组件已初始化`);
  234. }
  235. } else {
  236. console.warn(`[EnemyInstance] HPBar下未找到RedBar或YellowBar节点,RedBar: ${!!redBarNode}, YellowBar: ${!!yellowBarNode}`);
  237. }
  238. } else {
  239. console.warn(`[EnemyInstance] 未找到HPBar节点,无法初始化血条动画`);
  240. }
  241. }
  242. // 更新血量显示
  243. updateHealthDisplay(showBar: boolean = false) {
  244. // 确保血量值在有效范围内
  245. this.health = Math.max(0, Math.min(this.maxHealth, this.health));
  246. const healthProgress = this.maxHealth > 0 ? this.health / this.maxHealth : 0;
  247. console.log(`[EnemyInstance] 更新血量显示: ${this.health}/${this.maxHealth} (${(healthProgress * 100).toFixed(1)}%)`);
  248. // 使用血条动画组件更新血条
  249. if (this.hpBarAnimation) {
  250. this.hpBarAnimation.updateProgress(healthProgress, showBar);
  251. } else {
  252. // 备用方案:直接更新血条
  253. const hpBar = this.node.getChildByName('HPBar');
  254. if (hpBar) {
  255. const progressBar = hpBar.getComponent(ProgressBar);
  256. if (progressBar) {
  257. progressBar.progress = healthProgress;
  258. }
  259. // 根据showBar参数控制血条显示
  260. hpBar.active = showBar;
  261. }
  262. }
  263. // 更新血量数字
  264. const hpLabel = this.node.getChildByName('HPLabel');
  265. if (hpLabel) {
  266. const label = hpLabel.getComponent(Label);
  267. if (label) {
  268. // 显示整数血量值
  269. label.string = Math.ceil(this.health).toString();
  270. }
  271. }
  272. }
  273. // 受到伤害
  274. takeDamage(damage: number, isCritical: boolean = false) {
  275. // 如果已经死亡,不再处理伤害
  276. if (this.state === EnemyState.DEAD) {
  277. return;
  278. }
  279. // 确保伤害值为正数
  280. if (damage <= 0) {
  281. console.warn(`[EnemyInstance] 无效的伤害值: ${damage}`);
  282. return;
  283. }
  284. // 计算新的血量,确保不会低于0
  285. const oldHealth = this.health;
  286. const newHealth = Math.max(0, this.health - damage);
  287. const actualHealthLoss = oldHealth - newHealth; // 实际血量损失
  288. this.health = newHealth;
  289. // 日志显示武器的真实伤害值,而不是血量差值
  290. console.log(`[EnemyInstance] 敌人受到伤害: ${damage} (武器伤害), 实际血量损失: ${actualHealthLoss}, 剩余血量: ${this.health}/${this.maxHealth}`);
  291. // 受击音效已移除
  292. // 显示伤害数字动画(在敌人头顶)- 显示武器的真实伤害
  293. // 优先使用EnemyController节点上的DamageNumberAni组件实例
  294. if (this.controller) {
  295. const damageAni = this.controller.getComponent(DamageNumberAni);
  296. if (damageAni) {
  297. damageAni.showDamageNumber(damage, this.node.worldPosition, isCritical);
  298. } else {
  299. // 如果没有找到组件实例,使用静态方法作为备用
  300. DamageNumberAni.showDamageNumber(damage, this.node.worldPosition, isCritical);
  301. }
  302. } else {
  303. // 如果没有controller引用,使用静态方法
  304. DamageNumberAni.showDamageNumber(damage, this.node.worldPosition, isCritical);
  305. }
  306. // 更新血量显示和动画,受伤时显示血条
  307. this.updateHealthDisplay(true);
  308. // 如果血量低于等于0,销毁敌人
  309. if (this.health <= 0) {
  310. console.log(`[EnemyInstance] 敌人死亡,开始销毁流程`);
  311. this.state = EnemyState.DEAD;
  312. this.spawnCoin();
  313. // 进入死亡流程,禁用碰撞避免重复命中
  314. const col = this.getComponent(Collider2D);
  315. if (col) col.enabled = false;
  316. this.playDeathAnimationAndDestroy();
  317. }
  318. }
  319. onDestroy() {
  320. console.log(`[EnemyInstance] onDestroy 被调用,准备通知控制器`);
  321. // 通知控制器 & GameManager
  322. if (this.controller && typeof (this.controller as any).notifyEnemyDead === 'function') {
  323. // 检查控制器是否处于清理状态,避免在清理过程中触发游戏事件
  324. const isClearing = (this.controller as any).isClearing;
  325. if (isClearing) {
  326. console.log(`[EnemyInstance] 控制器处于清理状态,跳过死亡通知`);
  327. return;
  328. }
  329. console.log(`[EnemyInstance] 调用 notifyEnemyDead`);
  330. (this.controller as any).notifyEnemyDead(this.node);
  331. } else {
  332. console.warn(`[EnemyInstance] 无法调用 notifyEnemyDead: controller=${!!this.controller}`);
  333. }
  334. }
  335. update(deltaTime: number) {
  336. // 如果敌人被暂停,则不执行任何更新逻辑
  337. if (this.isPaused) {
  338. return;
  339. }
  340. if (this.state === EnemyState.MOVING) {
  341. this.updateMovement(deltaTime);
  342. } else if (this.state === EnemyState.ATTACKING) {
  343. this.updateAttack(deltaTime);
  344. }
  345. // 不再每帧播放攻击动画,避免日志刷屏
  346. }
  347. // 更新移动逻辑
  348. private updateMovement(deltaTime: number) {
  349. // 检查是否接近游戏区域边界
  350. if (this.checkNearGameArea()) {
  351. this.state = EnemyState.ATTACKING;
  352. this.attackTimer = 0;
  353. this.playAttackAnimation();
  354. return;
  355. }
  356. // 继续移动
  357. this.moveTowardsTarget(deltaTime);
  358. }
  359. // 检查是否接近游戏区域
  360. private checkNearGameArea(): boolean {
  361. const currentPos = this.node.worldPosition;
  362. // 获取游戏区域边界
  363. const gameArea = find('Canvas/GameLevelUI/GameArea');
  364. if (!gameArea) return false;
  365. const uiTransform = gameArea.getComponent(UITransform);
  366. if (!uiTransform) return false;
  367. const gameAreaPos = gameArea.worldPosition;
  368. const halfWidth = uiTransform.width / 2;
  369. const halfHeight = uiTransform.height / 2;
  370. const bounds = {
  371. left: gameAreaPos.x - halfWidth,
  372. right: gameAreaPos.x + halfWidth,
  373. top: gameAreaPos.y + halfHeight,
  374. bottom: gameAreaPos.y - halfHeight
  375. };
  376. // 检查是否在游戏区域内或非常接近
  377. const safeDistance = 50; // 安全距离
  378. const isInside = currentPos.x >= bounds.left - safeDistance &&
  379. currentPos.x <= bounds.right + safeDistance &&
  380. currentPos.y >= bounds.bottom - safeDistance &&
  381. currentPos.y <= bounds.top + safeDistance;
  382. if (isInside) {
  383. return true;
  384. }
  385. return false;
  386. }
  387. // 移动到目标位置
  388. private moveTowardsTarget(deltaTime: number) {
  389. // 使用世界坐标进行移动计算,确保不受父节点坐标系影响
  390. const currentWorldPos = this.node.worldPosition.clone();
  391. // 目标世界坐标:优先使用指定的 Fence,其次退化到游戏区域中心
  392. let targetWorldPos: Vec3;
  393. if (this.targetFence && this.targetFence.isValid) {
  394. targetWorldPos = this.targetFence.worldPosition.clone();
  395. } else {
  396. targetWorldPos = this.gameAreaCenter.clone();
  397. }
  398. const dir = targetWorldPos.subtract(currentWorldPos);
  399. if (dir.length() === 0) return;
  400. dir.normalize();
  401. const moveDistance = this.speed * deltaTime;
  402. const newWorldPos = currentWorldPos.add(dir.multiplyScalar(moveDistance));
  403. // 直接设置世界坐标
  404. this.node.setWorldPosition(newWorldPos);
  405. }
  406. // 更新攻击逻辑
  407. private updateAttack(deltaTime: number) {
  408. this.attackTimer -= deltaTime;
  409. if (this.attackTimer <= 0) {
  410. // 执行攻击
  411. this.performAttack();
  412. // 重置攻击计时器
  413. this.attackTimer = this.attackInterval;
  414. }
  415. }
  416. // 执行攻击
  417. private performAttack() {
  418. if (!this.controller) {
  419. return;
  420. }
  421. // 播放攻击音效
  422. EnemyAudio.playAttackSound(this.enemyConfig);
  423. // 对墙体造成伤害
  424. this.controller.damageWall(this.attackPower);
  425. }
  426. // 播放行走动画
  427. private playWalkAnimation() {
  428. if (!this.skeleton) return;
  429. const enemyComp = this.getComponent('EnemyComponent') as any;
  430. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  431. const walkName = anims.walk ?? 'walk';
  432. const idleName = anims.idle ?? 'idle';
  433. if (this.skeleton.findAnimation(walkName)) {
  434. this.skeleton.setAnimation(0, walkName, true);
  435. // 行走音效已移除
  436. } else if (this.skeleton.findAnimation(idleName)) {
  437. this.skeleton.setAnimation(0, idleName, true);
  438. }
  439. }
  440. // 播放攻击动画
  441. private playAttackAnimation() {
  442. if (!this.skeleton) return;
  443. const enemyComp2 = this.getComponent('EnemyComponent') as any;
  444. const anims2 = enemyComp2?.getAnimations ? enemyComp2.getAnimations() : {};
  445. const attackName = anims2.attack ?? 'attack';
  446. // 移除频繁打印
  447. if (this.skeleton.findAnimation(attackName)) {
  448. this.skeleton.setAnimation(0, attackName, true);
  449. }
  450. }
  451. private playDeathAnimationAndDestroy() {
  452. console.log(`[EnemyInstance] 开始播放死亡动画并销毁`);
  453. // 播放死亡音效
  454. EnemyAudio.playDeathSound(this.enemyConfig);
  455. if (this.skeleton) {
  456. const enemyComp = this.getComponent('EnemyComponent') as any;
  457. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  458. const deathName = anims.dead ?? 'dead';
  459. if (this.skeleton.findAnimation(deathName)) {
  460. this.skeleton.setAnimation(0, deathName, false);
  461. // 销毁节点在动画完毕后
  462. this.skeleton.setCompleteListener(() => {
  463. this.node.destroy();
  464. });
  465. return;
  466. }
  467. }
  468. this.node.destroy();
  469. }
  470. private spawnCoin() {
  471. const ctrl = this.controller as any; // EnemyController
  472. if (!ctrl?.coinPrefab) return;
  473. const coin = instantiate(ctrl.coinPrefab);
  474. find('Canvas')!.addChild(coin); // 放到 UI 层
  475. const pos = new Vec3();
  476. this.node.getWorldPosition(pos); // 取死亡敌人的世界坐标
  477. coin.worldPosition = pos; // 金币就在敌人身上出现
  478. }
  479. /**
  480. * 暂停敌人
  481. */
  482. public pause(): void {
  483. this.isPaused = true;
  484. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 已暂停`);
  485. }
  486. /**
  487. * 恢复敌人
  488. */
  489. public resume(): void {
  490. this.isPaused = false;
  491. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 已恢复`);
  492. }
  493. /**
  494. * 检查是否暂停
  495. */
  496. public isPausedState(): boolean {
  497. return this.isPaused;
  498. }
  499. /**
  500. * 重置血条状态(满血并隐藏)
  501. */
  502. public resetHealthBar(): void {
  503. if (this.hpBarAnimation) {
  504. this.hpBarAnimation.resetToFullAndHide();
  505. } else {
  506. // 备用方案:直接隐藏血条
  507. const hpBar = this.node.getChildByName('HPBar');
  508. if (hpBar) {
  509. hpBar.active = false;
  510. const progressBar = hpBar.getComponent(ProgressBar);
  511. if (progressBar) {
  512. progressBar.progress = 1.0;
  513. }
  514. }
  515. }
  516. }
  517. }