EnemyInstance.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. import { _decorator, Component, Node, ProgressBar, Label, Vec3, find, UITransform, Collider2D, Contact2DType, IPhysics2DContact, instantiate, resources, Prefab, JsonAsset, RigidBody2D, ERigidBody2DType, BoxCollider2D, CircleCollider2D } 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. private swayTime: number = 0; // 摆动时间累计
  50. private basePosition: Vec3 = new Vec3(); // 基础位置(摆动的中心点)
  51. private swayOffset: Vec3 = new Vec3(); // 当前摆动偏移
  52. // 攻击属性
  53. public attackInterval: number = 0; // 攻击间隔(秒),从配置文件读取
  54. private attackTimer: number = 0;
  55. // 对控制器的引用
  56. public controller: EnemyControllerType = null;
  57. // 敌人当前状态
  58. private state: EnemyState = EnemyState.MOVING;
  59. // 游戏区域中心
  60. private gameAreaCenter: Vec3 = new Vec3();
  61. // 碰撞的墙体
  62. private collidedWall: Node = null;
  63. // 骨骼动画组件
  64. private skeleton: sp.Skeleton | null = null;
  65. // 血条动画组件
  66. private hpBarAnimation: HPBarAnimation | null = null;
  67. // 暂停状态标记
  68. private isPaused: boolean = false;
  69. start() {
  70. // 初始化敌人
  71. this.initializeEnemy();
  72. }
  73. // 静态方法:加载敌人配置数据库
  74. public static async loadEnemyDatabase(): Promise<void> {
  75. if (EnemyInstance.enemyDatabase) return;
  76. return new Promise((resolve, reject) => {
  77. resources.load('data/enemies', JsonAsset, (err, jsonAsset) => {
  78. if (err) {
  79. console.error('[EnemyInstance] 加载敌人配置失败:', err);
  80. reject(err);
  81. return;
  82. }
  83. EnemyInstance.enemyDatabase = jsonAsset.json;
  84. resolve();
  85. });
  86. });
  87. }
  88. // 设置敌人配置
  89. public setEnemyConfig(enemyId: string): void {
  90. this.enemyId = enemyId;
  91. if (!EnemyInstance.enemyDatabase) {
  92. console.error('[EnemyInstance] 敌人配置数据库未加载');
  93. return;
  94. }
  95. // 从数据库中查找敌人配置
  96. // 修复:enemies.json是直接的数组结构,不需要.enemies包装
  97. const enemies = EnemyInstance.enemyDatabase;
  98. this.enemyConfig = enemies.find((enemy: any) => enemy.id === enemyId);
  99. if (!this.enemyConfig) {
  100. console.error(`[EnemyInstance] 未找到敌人配置: ${enemyId}`);
  101. return;
  102. }
  103. // 应用配置到敌人属性
  104. this.applyEnemyConfig();
  105. }
  106. // 应用敌人配置到属性
  107. private applyEnemyConfig(): void {
  108. if (!this.enemyConfig) return;
  109. // 从stats节点读取基础属性
  110. const stats = this.enemyConfig.stats || {};
  111. this.health = stats.health || 30;
  112. this.maxHealth = stats.maxHealth || this.health;
  113. // 从movement节点读取移动速度
  114. const movement = this.enemyConfig.movement || {};
  115. this.speed = movement.speed || 50;
  116. // 从combat节点读取攻击力
  117. const combat = this.enemyConfig.combat || {};
  118. this.attackPower = combat.attackDamage || 10;
  119. // 设置攻击间隔
  120. this.attackInterval = combat.attackCooldown || 2.0;
  121. }
  122. // 获取敌人配置信息
  123. public getEnemyConfig(): any {
  124. return this.enemyConfig;
  125. }
  126. // 获取敌人名称
  127. public getEnemyName(): string {
  128. return this.enemyConfig?.name || '未知敌人';
  129. }
  130. // 获取敌人类型
  131. public getEnemyType(): string {
  132. return this.enemyConfig?.type || 'basic';
  133. }
  134. // 获取敌人稀有度
  135. public getEnemyRarity(): string {
  136. return this.enemyConfig?.rarity || 'common';
  137. }
  138. // 获取金币奖励
  139. public getGoldReward(): number {
  140. return this.enemyConfig?.goldReward || 1;
  141. }
  142. // 初始化敌人
  143. private initializeEnemy() {
  144. // 确保血量正确设置
  145. if (this.maxHealth > 0) {
  146. this.health = this.maxHealth;
  147. }
  148. this.state = EnemyState.MOVING;
  149. // 只有在攻击间隔未设置时才使用默认值
  150. if (this.attackInterval <= 0) {
  151. this.attackInterval = 2.0; // 默认攻击间隔
  152. }
  153. this.attackTimer = 0;
  154. // 初始化血条动画组件
  155. this.initializeHPBarAnimation();
  156. // 初始化骨骼动画组件 - 从EnemySprite子节点获取
  157. const enemySprite = this.node.getChildByName('EnemySprite');
  158. if (enemySprite) {
  159. this.skeleton = enemySprite.getComponent(sp.Skeleton);
  160. } else {
  161. console.error('[EnemyInstance] 未找到EnemySprite子节点,无法获取骨骼动画组件');
  162. }
  163. this.playWalkAnimation();
  164. // 计算游戏区域中心
  165. this.calculateGameAreaCenter();
  166. // 初始化碰撞检测
  167. this.setupCollider();
  168. }
  169. // 设置碰撞器
  170. setupCollider() {
  171. // 从EnemySprite子节点获取碰撞器组件
  172. const enemySprite = this.node.getChildByName('EnemySprite');
  173. if (!enemySprite) {
  174. console.error('[EnemyInstance] 未找到EnemySprite子节点,无法设置碰撞器组件');
  175. return;
  176. }
  177. // 检查EnemySprite节点是否有碰撞器
  178. let collider = enemySprite.getComponent(Collider2D);
  179. if (!collider) {
  180. console.warn(`[EnemyInstance] 敌人节点 ${this.node.name} 的EnemySprite子节点没有碰撞器组件`);
  181. return;
  182. }
  183. // 确保有RigidBody2D组件,这对于碰撞检测是必需的
  184. let rigidBody = enemySprite.getComponent(RigidBody2D);
  185. if (!rigidBody) {
  186. console.log(`[EnemyInstance] 为敌人EnemySprite节点添加RigidBody2D组件`);
  187. rigidBody = enemySprite.addComponent(RigidBody2D);
  188. }
  189. // 设置刚体属性
  190. if (rigidBody) {
  191. rigidBody.type = ERigidBody2DType.Dynamic; // 动态刚体
  192. rigidBody.enabledContactListener = true; // 启用碰撞监听
  193. rigidBody.gravityScale = 0; // 不受重力影响
  194. rigidBody.linearDamping = 0; // 无线性阻尼
  195. rigidBody.angularDamping = 0; // 无角阻尼
  196. rigidBody.allowSleep = false; // 不允许休眠
  197. rigidBody.fixedRotation = true; // 固定旋转
  198. }
  199. // 根据ContentSize自适应碰撞体大小
  200. this.adaptColliderToContentSize(collider);
  201. // 设置碰撞事件监听
  202. collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  203. console.log(`[EnemyInstance] 敌人 ${this.node.name} 碰撞器设置完成,碰撞器启用: ${collider.enabled}, 刚体启用: ${rigidBody?.enabled}`);
  204. }
  205. /**
  206. * 根据ContentSize自适应碰撞体大小
  207. */
  208. private adaptColliderToContentSize(collider: Collider2D): void {
  209. // 从EnemySprite子节点获取UITransform组件
  210. const enemySprite = this.node.getChildByName('EnemySprite');
  211. if (!enemySprite) {
  212. console.error('[EnemyInstance] 未找到EnemySprite子节点,无法获取UITransform组件');
  213. return;
  214. }
  215. const uiTransform = enemySprite.getComponent(UITransform);
  216. if (!uiTransform) {
  217. console.warn(`[EnemyInstance] EnemySprite节点没有UITransform组件,无法自适应碰撞体大小`);
  218. return;
  219. }
  220. const contentSize = uiTransform.contentSize;
  221. console.log(`[EnemyInstance] 敌人 ${this.node.name} ContentSize: ${contentSize.width} x ${contentSize.height}`);
  222. // 根据碰撞器类型设置大小
  223. if (collider instanceof BoxCollider2D) {
  224. // 方形碰撞器:直接使用ContentSize
  225. const boxCollider = collider as BoxCollider2D;
  226. boxCollider.size.width = contentSize.width;
  227. boxCollider.size.height = contentSize.height;
  228. // 调整偏移量,使碰撞器居中
  229. const anchorPoint = uiTransform.anchorPoint;
  230. boxCollider.offset.x = (0.5 - anchorPoint.x) * contentSize.width;
  231. boxCollider.offset.y = (0.5 - anchorPoint.y) * contentSize.height;
  232. console.log(`[EnemyInstance] BoxCollider2D 已自适应: size(${boxCollider.size.width}, ${boxCollider.size.height}), offset(${boxCollider.offset.x.toFixed(2)}, ${boxCollider.offset.y.toFixed(2)})`);
  233. } else if (collider instanceof CircleCollider2D) {
  234. // 圆形碰撞器:使用ContentSize的较小值作为直径
  235. const circleCollider = collider as CircleCollider2D;
  236. const radius = Math.min(contentSize.width, contentSize.height) / 2;
  237. circleCollider.radius = radius;
  238. // 调整偏移量,使碰撞器居中
  239. const anchorPoint = uiTransform.anchorPoint;
  240. circleCollider.offset.x = (0.5 - anchorPoint.x) * contentSize.width;
  241. circleCollider.offset.y = (0.5 - anchorPoint.y) * contentSize.height;
  242. console.log(`[EnemyInstance] CircleCollider2D 已自适应: radius(${radius.toFixed(2)}), offset(${circleCollider.offset.x.toFixed(2)}, ${circleCollider.offset.y.toFixed(2)})`);
  243. } else {
  244. console.warn(`[EnemyInstance] 不支持的碰撞器类型: ${collider.constructor.name}`);
  245. }
  246. }
  247. // 碰撞开始事件
  248. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  249. const nodeName = otherCollider.node.name;
  250. // 如果碰到墙体,停止移动并开始攻击
  251. if (nodeName.includes('Wall') || nodeName.includes('wall') || nodeName.includes('Fence') || nodeName.includes('Jiguang')) {
  252. this.state = EnemyState.ATTACKING;
  253. this.attackTimer = 0; // 立即开始攻击
  254. // 切换攻击动画
  255. this.playAttackAnimation();
  256. }
  257. }
  258. // 获取节点路径
  259. getNodePath(node: Node): string {
  260. let path = node.name;
  261. let current = node;
  262. while (current.parent) {
  263. current = current.parent;
  264. path = current.name + '/' + path;
  265. }
  266. return path;
  267. }
  268. // 计算游戏区域中心
  269. private calculateGameAreaCenter() {
  270. const gameArea = find('Canvas/GameLevelUI/GameArea');
  271. if (gameArea) {
  272. this.gameAreaCenter = gameArea.worldPosition;
  273. }
  274. }
  275. /**
  276. * 初始化血条动画组件
  277. */
  278. private initializeHPBarAnimation() {
  279. const hpBar = this.node.getChildByName('HPBar');
  280. if (hpBar) {
  281. // 查找红色和黄色血条节点
  282. const redBarNode = hpBar.getChildByName('RedBar');
  283. const yellowBarNode = hpBar.getChildByName('YellowBar');
  284. if (redBarNode && yellowBarNode) {
  285. // 添加血条动画组件
  286. this.hpBarAnimation = this.node.addComponent(HPBarAnimation);
  287. if (this.hpBarAnimation) {
  288. // 正确设置红色和黄色血条节点引用
  289. this.hpBarAnimation.redBarNode = redBarNode;
  290. this.hpBarAnimation.yellowBarNode = yellowBarNode;
  291. this.hpBarAnimation.hpBarRootNode = hpBar; // 设置HPBar根节点
  292. console.log(`[EnemyInstance] 血条动画组件已初始化`);
  293. }
  294. } else {
  295. console.warn(`[EnemyInstance] HPBar下未找到RedBar或YellowBar节点,RedBar: ${!!redBarNode}, YellowBar: ${!!yellowBarNode}`);
  296. }
  297. } else {
  298. console.warn(`[EnemyInstance] 未找到HPBar节点,无法初始化血条动画`);
  299. }
  300. }
  301. // 更新血量显示
  302. updateHealthDisplay(showBar: boolean = false) {
  303. // 确保血量值在有效范围内
  304. this.health = Math.max(0, Math.min(this.maxHealth, this.health));
  305. const healthProgress = this.maxHealth > 0 ? this.health / this.maxHealth : 0;
  306. console.log(`[EnemyInstance] 更新血量显示: ${this.health}/${this.maxHealth} (${(healthProgress * 100).toFixed(1)}%)`);
  307. // 使用血条动画组件更新血条
  308. if (this.hpBarAnimation) {
  309. this.hpBarAnimation.updateProgress(healthProgress, showBar);
  310. } else {
  311. // 备用方案:直接更新血条
  312. const hpBar = this.node.getChildByName('HPBar');
  313. if (hpBar) {
  314. const progressBar = hpBar.getComponent(ProgressBar);
  315. if (progressBar) {
  316. progressBar.progress = healthProgress;
  317. }
  318. // 根据showBar参数控制血条显示
  319. hpBar.active = showBar;
  320. }
  321. }
  322. // 更新血量数字
  323. const hpLabel = this.node.getChildByName('HPLabel');
  324. if (hpLabel) {
  325. const label = hpLabel.getComponent(Label);
  326. if (label) {
  327. // 显示整数血量值
  328. label.string = Math.ceil(this.health).toString();
  329. }
  330. }
  331. }
  332. // 受到伤害
  333. takeDamage(damage: number, isCritical: boolean = false) {
  334. // 如果已经死亡,不再处理伤害
  335. if (this.state === EnemyState.DEAD) {
  336. return;
  337. }
  338. // 确保伤害值为正数
  339. if (damage <= 0) {
  340. console.warn(`[EnemyInstance] 无效的伤害值: ${damage}`);
  341. return;
  342. }
  343. // 应用防御力减少伤害
  344. const enemyComponent = this.getComponent(EnemyComponent);
  345. const defense = enemyComponent ? enemyComponent.getDefense() : 0;
  346. let finalDamage = Math.max(1, damage - defense); // 至少造成1点伤害
  347. // 检查格挡
  348. if (enemyComponent && enemyComponent.canBlock() && this.tryBlock()) {
  349. finalDamage *= (1 - enemyComponent.getBlockDamageReduction());
  350. this.showBlockEffect();
  351. }
  352. // 计算新的血量,确保不会低于0
  353. const oldHealth = this.health;
  354. const newHealth = Math.max(0, this.health - finalDamage);
  355. const actualHealthLoss = oldHealth - newHealth; // 实际血量损失
  356. this.health = newHealth;
  357. // 检查是否触发狂暴
  358. this.checkRageTrigger();
  359. // 日志显示武器的真实伤害值,而不是血量差值
  360. console.log(`[EnemyInstance] 敌人受到伤害: ${damage} (武器伤害), 防御后伤害: ${finalDamage}, 实际血量损失: ${actualHealthLoss}, 剩余血量: ${this.health}/${this.maxHealth}`);
  361. // 受击音效已移除
  362. // 显示伤害数字动画(在敌人头顶)- 显示防御后的实际伤害
  363. // 优先使用EnemyController节点上的DamageNumberAni组件实例
  364. if (this.controller) {
  365. const damageAni = this.controller.getComponent(DamageNumberAni);
  366. if (damageAni) {
  367. damageAni.showDamageNumber(finalDamage, this.node.worldPosition, isCritical);
  368. } else {
  369. // 如果没有找到组件实例,使用静态方法作为备用
  370. DamageNumberAni.showDamageNumber(finalDamage, this.node.worldPosition, isCritical);
  371. }
  372. } else {
  373. // 如果没有controller引用,使用静态方法
  374. DamageNumberAni.showDamageNumber(finalDamage, this.node.worldPosition, isCritical);
  375. }
  376. // 更新血量显示和动画,受伤时显示血条
  377. this.updateHealthDisplay(true);
  378. // 如果血量低于等于0,销毁敌人
  379. if (this.health <= 0) {
  380. console.log(`[EnemyInstance] 敌人死亡,开始销毁流程`);
  381. this.state = EnemyState.DEAD;
  382. this.spawnCoin();
  383. // 进入死亡流程,禁用碰撞避免重复命中
  384. const enemySprite = this.node.getChildByName('EnemySprite');
  385. if (enemySprite) {
  386. const col = enemySprite.getComponent(Collider2D);
  387. if (col) col.enabled = false;
  388. }
  389. this.playDeathAnimationAndDestroy();
  390. }
  391. }
  392. onDestroy() {
  393. console.log(`[EnemyInstance] onDestroy 被调用,准备通知控制器`);
  394. // 通知控制器 & GameManager
  395. if (this.controller && typeof (this.controller as any).notifyEnemyDead === 'function') {
  396. // 检查控制器是否处于清理状态,避免在清理过程中触发游戏事件
  397. const isClearing = (this.controller as any).isClearing;
  398. if (isClearing) {
  399. console.log(`[EnemyInstance] 控制器处于清理状态,跳过死亡通知`);
  400. return;
  401. }
  402. console.log(`[EnemyInstance] 调用 notifyEnemyDead`);
  403. (this.controller as any).notifyEnemyDead(this.node);
  404. } else {
  405. console.warn(`[EnemyInstance] 无法调用 notifyEnemyDead: controller=${!!this.controller}`);
  406. }
  407. }
  408. update(deltaTime: number) {
  409. // 如果敌人被暂停,则不执行任何更新逻辑
  410. if (this.isPaused) {
  411. return;
  412. }
  413. if (this.state === EnemyState.MOVING) {
  414. this.updateMovement(deltaTime);
  415. } else if (this.state === EnemyState.ATTACKING) {
  416. this.updateAttack(deltaTime);
  417. }
  418. // 不再每帧播放攻击动画,避免日志刷屏
  419. }
  420. // 更新移动逻辑
  421. private updateMovement(deltaTime: number) {
  422. // 继续移动到目标墙体
  423. this.moveTowardsTarget(deltaTime);
  424. }
  425. // 移动到目标位置
  426. private moveTowardsTarget(deltaTime: number) {
  427. // 使用世界坐标进行移动计算,确保不受父节点坐标系影响
  428. const currentWorldPos = this.node.worldPosition.clone();
  429. // 目标世界坐标:优先使用指定的 Fence,其次退化到游戏区域中心
  430. let targetWorldPos: Vec3;
  431. if (this.targetFence && this.targetFence.isValid) {
  432. targetWorldPos = this.targetFence.worldPosition.clone();
  433. } else {
  434. targetWorldPos = this.gameAreaCenter.clone();
  435. }
  436. const dir = targetWorldPos.subtract(currentWorldPos);
  437. if (dir.length() === 0) return;
  438. dir.normalize();
  439. // 获取当前速度(考虑狂暴加成)
  440. const enemyComponent = this.getComponent(EnemyComponent);
  441. const currentSpeed = enemyComponent ? enemyComponent.getCurrentSpeed() : this.speed;
  442. const moveDistance = currentSpeed * deltaTime;
  443. let newWorldPos = currentWorldPos.add(dir.multiplyScalar(moveDistance));
  444. // 应用摆动效果
  445. if (enemyComponent) {
  446. const swayAmplitude = enemyComponent.getSwingAmplitude();
  447. const swayFrequency = enemyComponent.getSwingFrequency();
  448. if (swayAmplitude > 0 && swayFrequency > 0) {
  449. this.swayTime += deltaTime;
  450. // 计算垂直于移动方向的摆动偏移
  451. const swayOffset = Math.sin(this.swayTime * swayFrequency * 2 * Math.PI) * swayAmplitude;
  452. // 计算垂直于移动方向的向量
  453. const perpDir = new Vec3(-dir.y, dir.x, 0);
  454. const swayVector = perpDir.multiplyScalar(swayOffset);
  455. newWorldPos = newWorldPos.add(swayVector);
  456. }
  457. }
  458. // 直接设置世界坐标
  459. this.node.setWorldPosition(newWorldPos);
  460. }
  461. // 更新攻击逻辑
  462. private updateAttack(deltaTime: number) {
  463. this.attackTimer -= deltaTime;
  464. if (this.attackTimer <= 0) {
  465. // 执行攻击
  466. this.performAttack();
  467. // 重置攻击计时器
  468. this.attackTimer = this.attackInterval;
  469. }
  470. }
  471. // 执行攻击
  472. private performAttack() {
  473. if (!this.controller) {
  474. return;
  475. }
  476. const enemyComponent = this.getComponent(EnemyComponent);
  477. const attackType = enemyComponent ? enemyComponent.getAttackType() : 'melee';
  478. // 播放攻击音效
  479. EnemyAudio.playAttackSound(this.enemyConfig);
  480. // 根据攻击类型执行不同的攻击逻辑
  481. if (attackType === 'ranged' || attackType === 'projectile') {
  482. this.performRangedAttack();
  483. } else {
  484. // 近战攻击:播放攻击动画,动画结束后造成伤害
  485. this.playAttackAnimationWithDamage();
  486. }
  487. }
  488. // 执行远程攻击(投掷)
  489. private performRangedAttack() {
  490. const enemyComponent = this.getComponent(EnemyComponent);
  491. if (!enemyComponent) return;
  492. const projectileType = enemyComponent.getProjectileType();
  493. const projectileSpeed = enemyComponent.getProjectileSpeed();
  494. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 发射投掷物: ${projectileType}, 速度: ${projectileSpeed}`);
  495. // TODO: 实际创建和发射投掷物的逻辑
  496. // 这里需要根据项目的投掷物系统来实现
  497. // 例如:创建投掷物预制体,设置速度和方向,添加碰撞检测等
  498. // 暂时直接造成伤害作为占位符
  499. this.scheduleOnce(() => {
  500. this.dealDamageToWall();
  501. }, 1.0); // 1秒后造成伤害,模拟投掷物飞行时间
  502. }
  503. // 播放行走动画
  504. private playWalkAnimation() {
  505. if (!this.skeleton) return;
  506. const enemyComp = this.getComponent('EnemyComponent') as any;
  507. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  508. const walkName = anims.walk ?? 'walk';
  509. const idleName = anims.idle ?? 'idle';
  510. if (this.skeleton.findAnimation(walkName)) {
  511. this.skeleton.setAnimation(0, walkName, true);
  512. // 行走音效已移除
  513. } else if (this.skeleton.findAnimation(idleName)) {
  514. this.skeleton.setAnimation(0, idleName, true);
  515. }
  516. }
  517. // 播放攻击动画
  518. private playAttackAnimation() {
  519. if (!this.skeleton) return;
  520. const enemyComp2 = this.getComponent('EnemyComponent') as any;
  521. const anims2 = enemyComp2?.getAnimations ? enemyComp2.getAnimations() : {};
  522. const attackName = anims2.attack ?? 'attack';
  523. // 移除频繁打印
  524. if (this.skeleton.findAnimation(attackName)) {
  525. this.skeleton.setAnimation(0, attackName, true);
  526. }
  527. }
  528. // 播放攻击动画并在动画结束时造成伤害
  529. private playAttackAnimationWithDamage() {
  530. if (!this.skeleton) {
  531. // 如果没有骨骼动画,直接造成伤害
  532. this.dealDamageToWall();
  533. return;
  534. }
  535. const enemyComp = this.getComponent('EnemyComponent') as any;
  536. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  537. const attackName = anims.attack ?? 'attack';
  538. const animation = this.skeleton.findAnimation(attackName);
  539. if (animation) {
  540. // 播放攻击动画(不循环)
  541. this.skeleton.setAnimation(0, attackName, false);
  542. // 获取动画时长并在动画结束时造成伤害
  543. const animationDuration = animation.duration;
  544. console.log(`[EnemyInstance] 攻击动画时长: ${animationDuration}秒`);
  545. // 使用定时器在动画结束时造成伤害
  546. this.scheduleOnce(() => {
  547. this.dealDamageToWall();
  548. // 动画完成后切换回行走动画
  549. this.playWalkAnimation();
  550. }, animationDuration);
  551. } else {
  552. // 如果找不到攻击动画,直接造成伤害
  553. this.dealDamageToWall();
  554. }
  555. }
  556. // 对墙体造成伤害
  557. private dealDamageToWall() {
  558. if (this.controller) {
  559. // 获取当前攻击力(考虑狂暴加成)
  560. const enemyComponent = this.getComponent(EnemyComponent);
  561. const currentAttackPower = enemyComponent ? enemyComponent.getCurrentAttackPower() : this.attackPower;
  562. this.controller.damageWall(currentAttackPower);
  563. }
  564. }
  565. private playDeathAnimationAndDestroy() {
  566. console.log(`[EnemyInstance] 开始播放死亡动画并销毁`);
  567. // 播放死亡音效
  568. EnemyAudio.playDeathSound(this.enemyConfig);
  569. if (this.skeleton) {
  570. const enemyComp = this.getComponent('EnemyComponent') as any;
  571. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  572. const deathName = anims.dead ?? 'dead';
  573. if (this.skeleton.findAnimation(deathName)) {
  574. this.skeleton.setAnimation(0, deathName, false);
  575. // 销毁节点在动画完毕后
  576. this.skeleton.setCompleteListener(() => {
  577. this.node.destroy();
  578. });
  579. return;
  580. }
  581. }
  582. this.node.destroy();
  583. }
  584. private spawnCoin() {
  585. const ctrl = this.controller as any; // EnemyController
  586. if (!ctrl?.coinPrefab) return;
  587. const coin = instantiate(ctrl.coinPrefab);
  588. find('Canvas')!.addChild(coin); // 放到 UI 层
  589. const pos = new Vec3();
  590. this.node.getWorldPosition(pos); // 取死亡敌人的世界坐标
  591. coin.worldPosition = pos; // 金币就在敌人身上出现
  592. }
  593. /**
  594. * 暂停敌人
  595. */
  596. public pause(): void {
  597. this.isPaused = true;
  598. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 已暂停`);
  599. }
  600. /**
  601. * 恢复敌人
  602. */
  603. public resume(): void {
  604. this.isPaused = false;
  605. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 已恢复`);
  606. }
  607. /**
  608. * 检查是否暂停
  609. */
  610. public isPausedState(): boolean {
  611. return this.isPaused;
  612. }
  613. /**
  614. * 重置血条状态(满血并隐藏)
  615. */
  616. public resetHealthBar(): void {
  617. if (this.hpBarAnimation) {
  618. this.hpBarAnimation.resetToFullAndHide();
  619. } else {
  620. // 备用方案:直接隐藏血条
  621. const hpBar = this.node.getChildByName('HPBar');
  622. if (hpBar) {
  623. hpBar.active = false;
  624. const progressBar = hpBar.getComponent(ProgressBar);
  625. if (progressBar) {
  626. progressBar.progress = 1.0;
  627. }
  628. }
  629. }
  630. }
  631. /**
  632. * 尝试格挡攻击
  633. */
  634. private tryBlock(): boolean {
  635. const enemyComponent = this.getComponent(EnemyComponent);
  636. if (!enemyComponent) return false;
  637. const blockChance = enemyComponent.getBlockChance();
  638. return Math.random() < blockChance;
  639. }
  640. /**
  641. * 显示格挡效果
  642. */
  643. private showBlockEffect(): void {
  644. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 格挡了攻击`);
  645. // TODO: 添加格挡视觉效果
  646. }
  647. /**
  648. * 检查是否触发狂暴状态
  649. */
  650. private checkRageTrigger(): void {
  651. const enemyComponent = this.getComponent(EnemyComponent);
  652. if (!enemyComponent) return;
  653. const healthPercent = this.health / this.maxHealth;
  654. const rageTriggerThreshold = enemyComponent.getRageTriggerThreshold();
  655. if (healthPercent <= rageTriggerThreshold && !enemyComponent.isInRage()) {
  656. enemyComponent.triggerRage();
  657. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 进入狂暴状态`);
  658. }
  659. }
  660. }