EnemyInstance.ts 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  1. import { _decorator, Component, Node, ProgressBar, Label, Vec3, find, UITransform, Collider2D, Contact2DType, IPhysics2DContact, instantiate, resources, Prefab, JsonAsset, RigidBody2D, ERigidBody2DType, BoxCollider2D, CircleCollider2D, Vec2, Color, UIOpacity, tween } from 'cc';
  2. import { JsonConfigLoader } from '../Core/JsonConfigLoader';
  3. import { sp } from 'cc';
  4. import { DamageNumberAni } from '../Animations/DamageNumberAni';
  5. import { HPBarAnimation } from '../Animations/HPBarAnimation';
  6. import { EnemyComponent } from './EnemyComponent';
  7. import { EnemyAudio } from '../AudioManager/EnemyAudios';
  8. import { ScreenShakeManager } from './EnemyWeapon/ScreenShakeManager';
  9. import EventBus, { GameEvents } from '../Core/EventBus';
  10. const { ccclass, property } = _decorator;
  11. // 前向声明EnemyController接口,避免循环引用
  12. interface EnemyControllerType {
  13. gameBounds: {
  14. left: number;
  15. right: number;
  16. top: number;
  17. bottom: number;
  18. };
  19. topFenceNode: Node;
  20. bottomFenceNode: Node;
  21. damageWall: (damage: number) => void;
  22. getComponent: (componentType: any) => any;
  23. }
  24. // 敌人状态枚举
  25. enum EnemyState {
  26. DRIFTING, // 漂移中(从生成位置移动到线上)
  27. MOVING, // 移动中
  28. IDLE, // 待机中(碰到墙体后停止移动但可以攻击)
  29. ATTACKING, // 攻击中
  30. DEAD // 死亡
  31. }
  32. // 单个敌人实例的组件
  33. @ccclass('EnemyInstance')
  34. export class EnemyInstance extends Component {
  35. // 敌人属性(从配置文件读取)
  36. public health: number = 0;
  37. public maxHealth: number = 0;
  38. public speed: number = 0;
  39. public attackPower: number = 0;
  40. // 敌人配置ID
  41. public enemyId: string = '';
  42. // 敌人配置数据
  43. private enemyConfig: any = null;
  44. // 敌人配置数据库
  45. private static enemyDatabase: any = null;
  46. // === 新增属性 ===
  47. /** 是否从上方生成 */
  48. public spawnFromTop: boolean = true;
  49. /** 目标 Fence 节点(TopFence / BottomFence) */
  50. public targetFence: Node | null = null;
  51. /** 目标位置(墙体上的随机点) */
  52. public targetPosition: Vec3 | null = null;
  53. /** 漂移目标位置(线上的位置) */
  54. public driftTargetPosition: Vec3 | null = null;
  55. // 移动相关属性
  56. public movingDirection: number = 1; // 1: 向右, -1: 向左
  57. public targetY: number = 0; // 目标Y位置
  58. public changeDirectionTime: number = 0; // 下次改变方向的时间
  59. // 移动配置属性(从配置文件读取)
  60. public movementPattern: string = 'direct'; // 移动模式:direct, patrol等
  61. public moveType: string = 'straight'; // 移动类型:straight, sway等
  62. public patrolRange: number = 100; // 巡逻范围
  63. public rotationSpeed: number = 90; // 旋转速度
  64. public speedVariation: number = 0; // 速度变化
  65. public swingAmplitude: number = 0; // 摆动幅度
  66. public swingFrequency: number = 1; // 摆动频率
  67. // 摆动移动相关属性
  68. private swayTime: number = 0; // 摆动时间累计
  69. private basePosition: Vec3 = new Vec3(); // 基础位置(摆动的中心点)
  70. private swayOffset: Vec3 = new Vec3(); // 当前摆动偏移
  71. // 攻击属性
  72. public attackInterval: number = 0; // 攻击间隔(秒),从配置文件读取
  73. private attackTimer: number = 0;
  74. // 对控制器的引用
  75. public controller: EnemyControllerType = null;
  76. // 敌人当前状态
  77. private state: EnemyState = EnemyState.DRIFTING;
  78. // 游戏区域中心
  79. private gameAreaCenter: Vec3 = new Vec3();
  80. // 碰撞的墙体
  81. private collidedWall: Node = null;
  82. // 骨骼动画组件
  83. private skeleton: sp.Skeleton | null = null;
  84. // 血条动画组件
  85. private hpBarAnimation: HPBarAnimation | null = null;
  86. // 暂停状态标记
  87. private isPaused: boolean = false;
  88. start() {
  89. // 初始化敌人
  90. this.initializeEnemy();
  91. }
  92. // 静态方法:加载敌人配置数据库
  93. public static async loadEnemyDatabase(): Promise<void> {
  94. if (EnemyInstance.enemyDatabase) return;
  95. try {
  96. EnemyInstance.enemyDatabase = await JsonConfigLoader.getInstance().loadConfig('enemies');
  97. if (!EnemyInstance.enemyDatabase) {
  98. throw new Error('敌人配置文件内容为空');
  99. }
  100. } catch (error) {
  101. console.error('[EnemyInstance] 加载敌人配置失败:', error);
  102. throw error;
  103. }
  104. }
  105. // 设置敌人配置
  106. public setEnemyConfig(enemyId: string): void {
  107. this.enemyId = enemyId;
  108. if (!EnemyInstance.enemyDatabase) {
  109. console.error('[EnemyInstance] 敌人配置数据库未加载');
  110. return;
  111. }
  112. // 从数据库中查找敌人配置
  113. // 修复:enemies.json是直接的数组结构,不需要.enemies包装
  114. const enemies = EnemyInstance.enemyDatabase;
  115. this.enemyConfig = enemies.find((enemy: any) => enemy.id === enemyId);
  116. if (!this.enemyConfig) {
  117. console.error(`[EnemyInstance] 未找到敌人配置: ${enemyId}`);
  118. return;
  119. }
  120. // 应用配置到敌人属性
  121. this.applyEnemyConfig();
  122. }
  123. // 应用敌人配置到属性
  124. private applyEnemyConfig(): void {
  125. if (!this.enemyConfig) return;
  126. // 从stats节点读取基础属性
  127. const stats = this.enemyConfig.stats || {};
  128. this.health = stats.health || 30;
  129. this.maxHealth = stats.maxHealth || this.health;
  130. // 从movement节点读取移动配置
  131. const movement = this.enemyConfig.movement || {};
  132. this.speed = movement.speed || 50;
  133. // 读取移动模式配置
  134. this.movementPattern = movement.pattern || 'direct';
  135. this.moveType = movement.moveType || 'straight';
  136. this.patrolRange = movement.patrolRange || 100;
  137. this.rotationSpeed = movement.rotationSpeed || 90;
  138. this.speedVariation = movement.speedVariation || 0;
  139. // 读取摆动配置
  140. this.swingAmplitude = movement.swingAmplitude || 0;
  141. this.swingFrequency = movement.swingFrequency || 1;
  142. // 从combat节点读取攻击力
  143. const combat = this.enemyConfig.combat || {};
  144. this.attackPower = combat.attackDamage || 10;
  145. // 设置攻击间隔
  146. this.attackInterval = combat.attackCooldown || 2.0;
  147. console.log(`[EnemyInstance] 应用配置 ${this.enemyId}: 移动模式=${this.movementPattern}, 移动类型=${this.moveType}, 速度=${this.speed}, 摆动幅度=${this.swingAmplitude}`);
  148. }
  149. // 获取敌人配置信息
  150. public getEnemyConfig(): any {
  151. return this.enemyConfig;
  152. }
  153. // 获取敌人名称
  154. public getEnemyName(): string {
  155. return this.enemyConfig?.name || '未知敌人';
  156. }
  157. // 获取敌人类型
  158. public getEnemyType(): string {
  159. return this.enemyConfig?.type || 'basic';
  160. }
  161. // 获取敌人稀有度
  162. public getEnemyRarity(): string {
  163. return this.enemyConfig?.rarity || 'common';
  164. }
  165. // 获取金币奖励
  166. public getGoldReward(): number {
  167. return this.enemyConfig?.goldReward || 1;
  168. }
  169. // 获取掉落金币数量
  170. public getDropCoins(): number {
  171. const stats = this.enemyConfig?.stats || {};
  172. return stats.dropCoins || 1;
  173. }
  174. // 初始化敌人
  175. private initializeEnemy() {
  176. // 确保血量正确设置
  177. if (this.maxHealth > 0) {
  178. this.health = this.maxHealth;
  179. }
  180. this.state = EnemyState.DRIFTING; // 从漂移状态开始
  181. // 只有在攻击间隔未设置时才使用默认值
  182. if (this.attackInterval <= 0) {
  183. this.attackInterval = 2.0; // 默认攻击间隔
  184. }
  185. this.attackTimer = 0;
  186. // 初始化血条动画组件
  187. this.initializeHPBarAnimation();
  188. // 初始化骨骼动画组件 - 从EnemySprite子节点获取
  189. const enemySprite = this.node.getChildByName('EnemySprite');
  190. if (enemySprite) {
  191. this.skeleton = enemySprite.getComponent(sp.Skeleton);
  192. } else {
  193. console.error('[EnemyInstance] 未找到EnemySprite子节点,无法获取骨骼动画组件');
  194. }
  195. this.playWalkAnimation();
  196. // 计算游戏区域中心
  197. this.calculateGameAreaCenter();
  198. // 初始化碰撞检测
  199. this.setupCollider();
  200. }
  201. // 设置碰撞器
  202. setupCollider() {
  203. // 从EnemySprite子节点获取碰撞器组件
  204. const enemySprite = this.node.getChildByName('EnemySprite');
  205. if (!enemySprite) {
  206. console.error('[EnemyInstance] 未找到EnemySprite子节点,无法设置碰撞器组件');
  207. return;
  208. }
  209. // 检查EnemySprite节点是否有碰撞器
  210. let collider = enemySprite.getComponent(Collider2D);
  211. if (!collider) {
  212. console.warn(`[EnemyInstance] 敌人节点 ${this.node.name} 的EnemySprite子节点没有碰撞器组件`);
  213. return;
  214. }
  215. // 确保有RigidBody2D组件,这对于碰撞检测是必需的
  216. let rigidBody = enemySprite.getComponent(RigidBody2D);
  217. if (!rigidBody) {
  218. console.log(`[EnemyInstance] 为敌人EnemySprite节点添加RigidBody2D组件`);
  219. rigidBody = enemySprite.addComponent(RigidBody2D);
  220. }
  221. // 设置刚体属性
  222. if (rigidBody) {
  223. rigidBody.type = ERigidBody2DType.Dynamic; // 动态刚体
  224. rigidBody.enabledContactListener = true; // 启用碰撞监听
  225. rigidBody.gravityScale = 0; // 不受重力影响
  226. rigidBody.linearDamping = 0; // 无线性阻尼
  227. rigidBody.angularDamping = 0; // 无角阻尼
  228. rigidBody.allowSleep = false; // 不允许休眠
  229. rigidBody.fixedRotation = true; // 固定旋转
  230. }
  231. // 根据ContentSize自适应碰撞体大小
  232. this.adaptColliderToContentSize(collider);
  233. // 设置碰撞事件监听
  234. collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  235. console.log(`[EnemyInstance] 敌人 ${this.node.name} 碰撞器设置完成,碰撞器启用: ${collider.enabled}, 刚体启用: ${rigidBody?.enabled}`);
  236. }
  237. /**
  238. * 根据ContentSize自适应碰撞体大小
  239. */
  240. private adaptColliderToContentSize(collider: Collider2D): void {
  241. // 从EnemySprite子节点获取UITransform组件
  242. const enemySprite = this.node.getChildByName('EnemySprite');
  243. if (!enemySprite) {
  244. console.error('[EnemyInstance] 未找到EnemySprite子节点,无法获取UITransform组件');
  245. return;
  246. }
  247. const uiTransform = enemySprite.getComponent(UITransform);
  248. if (!uiTransform) {
  249. console.warn(`[EnemyInstance] EnemySprite节点没有UITransform组件,无法自适应碰撞体大小`);
  250. return;
  251. }
  252. // 尝试获取骨骼动画组件来获取更准确的尺寸
  253. const skeleton = enemySprite.getComponent(sp.Skeleton);
  254. let actualWidth = uiTransform.contentSize.width;
  255. let actualHeight = uiTransform.contentSize.height;
  256. if (skeleton && skeleton.skeletonData) {
  257. // 如果有骨骼动画,尝试从骨骼数据获取尺寸信息
  258. try {
  259. // 使用骨骼数据的默认尺寸,或者根据动画缩放计算
  260. const skeletonData = skeleton.skeletonData;
  261. if (skeletonData) {
  262. // 获取骨骼的缩放比例
  263. const scaleX = Math.abs(skeleton.node.scale.x);
  264. const scaleY = Math.abs(skeleton.node.scale.y);
  265. // 使用合理的默认尺寸并应用缩放
  266. actualWidth = Math.max(60 * scaleX, uiTransform.contentSize.width * 0.8);
  267. actualHeight = Math.max(80 * scaleY, uiTransform.contentSize.height * 0.8);
  268. console.log(`[EnemyInstance] 使用骨骼动画尺寸 (scale: ${scaleX.toFixed(2)}, ${scaleY.toFixed(2)}): ${actualWidth.toFixed(2)} x ${actualHeight.toFixed(2)}`);
  269. } else {
  270. // 如果无法获取骨骼数据,使用默认尺寸
  271. actualWidth = Math.max(60, uiTransform.contentSize.width * 0.8);
  272. actualHeight = Math.max(80, uiTransform.contentSize.height * 0.8);
  273. console.log(`[EnemyInstance] 使用默认骨骼尺寸: ${actualWidth.toFixed(2)} x ${actualHeight.toFixed(2)}`);
  274. }
  275. } catch (error) {
  276. console.warn(`[EnemyInstance] 获取骨骼信息失败,使用默认尺寸:`, error);
  277. actualWidth = Math.max(60, uiTransform.contentSize.width * 0.8);
  278. actualHeight = Math.max(80, uiTransform.contentSize.height * 0.8);
  279. }
  280. }
  281. console.log(`[EnemyInstance] 敌人 ${this.node.name} 实际尺寸: ${actualWidth.toFixed(2)} x ${actualHeight.toFixed(2)}`);
  282. // 根据碰撞器类型设置大小
  283. if (collider instanceof BoxCollider2D) {
  284. // 方形碰撞器:使用实际尺寸,稍微缩小以避免过于敏感的碰撞
  285. const boxCollider = collider as BoxCollider2D;
  286. boxCollider.size.width = actualWidth * 0.9; // 缩小10%
  287. boxCollider.size.height = actualHeight * 0.9; // 缩小10%
  288. // 调整偏移量,使碰撞器居中对齐到EnemySprite
  289. const anchorPoint = uiTransform.anchorPoint;
  290. // 对于骨骼动画,通常锚点在底部中心(0.5, 0),需要向上偏移
  291. boxCollider.offset.x = 0; // X轴居中
  292. boxCollider.offset.y = actualHeight * (0.5 - anchorPoint.y) * 0.9; // Y轴根据锚点调整,并匹配缩放后的尺寸
  293. console.log(`[EnemyInstance] BoxCollider2D 已自适应: size(${boxCollider.size.width.toFixed(2)}, ${boxCollider.size.height.toFixed(2)}), offset(${boxCollider.offset.x.toFixed(2)}, ${boxCollider.offset.y.toFixed(2)}), anchor(${anchorPoint.x.toFixed(2)}, ${anchorPoint.y.toFixed(2)})`);
  294. } else if (collider instanceof CircleCollider2D) {
  295. // 圆形碰撞器:使用实际尺寸的较小值作为直径,稍微缩小
  296. const circleCollider = collider as CircleCollider2D;
  297. const radius = Math.min(actualWidth, actualHeight) / 2 * 0.9; // 缩小10%
  298. circleCollider.radius = radius;
  299. // 调整偏移量,使碰撞器居中对齐到EnemySprite
  300. const anchorPoint = uiTransform.anchorPoint;
  301. // 对于骨骼动画,通常锚点在底部中心(0.5, 0),需要向上偏移
  302. circleCollider.offset.x = 0; // X轴居中
  303. circleCollider.offset.y = actualHeight * (0.5 - anchorPoint.y) * 0.9; // Y轴根据锚点调整,并匹配缩放后的尺寸
  304. console.log(`[EnemyInstance] CircleCollider2D 已自适应: radius(${radius.toFixed(2)}), offset(${circleCollider.offset.x.toFixed(2)}, ${circleCollider.offset.y.toFixed(2)}), anchor(${anchorPoint.x.toFixed(2)}, ${anchorPoint.y.toFixed(2)})`);
  305. } else {
  306. console.warn(`[EnemyInstance] 不支持的碰撞器类型: ${collider.constructor.name}`);
  307. }
  308. // 碰撞体调整完成后,同步更新血条位置
  309. this.updateHPBarPosition();
  310. }
  311. /**
  312. * 动态调整血条位置,使其始终显示在碰撞体上方
  313. */
  314. private updateHPBarPosition(): void {
  315. // 获取血条根节点
  316. const hpBarRoot = this.node.getChildByName('HPBar');
  317. if (!hpBarRoot) {
  318. console.warn('[EnemyInstance] 未找到HPBar节点,无法调整血条位置');
  319. return;
  320. }
  321. // 获取EnemySprite节点和其碰撞器
  322. const enemySprite = this.node.getChildByName('EnemySprite');
  323. if (!enemySprite) {
  324. console.error('[EnemyInstance] 未找到EnemySprite子节点,无法计算血条位置');
  325. return;
  326. }
  327. const collider = enemySprite.getComponent(Collider2D);
  328. const uiTransform = enemySprite.getComponent(UITransform);
  329. if (!collider || !uiTransform) {
  330. console.warn('[EnemyInstance] EnemySprite节点缺少必要组件,无法计算血条位置');
  331. return;
  332. }
  333. // 计算碰撞体的顶部位置
  334. let colliderTopY = 0;
  335. const anchorPoint = uiTransform.anchorPoint;
  336. if (collider instanceof BoxCollider2D) {
  337. const boxCollider = collider as BoxCollider2D;
  338. // 碰撞体顶部 = 碰撞体偏移Y + 碰撞体高度的一半
  339. colliderTopY = boxCollider.offset.y + boxCollider.size.height / 2;
  340. } else if (collider instanceof CircleCollider2D) {
  341. const circleCollider = collider as CircleCollider2D;
  342. // 碰撞体顶部 = 碰撞体偏移Y + 半径
  343. colliderTopY = circleCollider.offset.y + circleCollider.radius;
  344. }
  345. // 血条位置设置为碰撞体顶部上方一定距离
  346. const hpBarOffset = -35; // 血条距离碰撞体顶部的距离
  347. const hpBarY = colliderTopY + hpBarOffset;
  348. // 设置血条位置
  349. const hpBarTransform = hpBarRoot.getComponent(UITransform);
  350. if (hpBarTransform) {
  351. hpBarRoot.setPosition(0, hpBarY, 0);
  352. console.log(`[EnemyInstance] 血条位置已更新: Y = ${hpBarY.toFixed(2)} (碰撞体顶部: ${colliderTopY.toFixed(2)})`);
  353. }
  354. }
  355. // 碰撞开始事件
  356. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  357. const nodeName = otherCollider.node.name;
  358. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 碰撞检测 - 碰撞对象: ${nodeName}, 当前状态: ${EnemyState[this.state]}`);
  359. // 只有在移动状态或攻击状态下才能响应墙体碰撞,避免重复触发
  360. if (this.state !== EnemyState.MOVING && this.state !== EnemyState.ATTACKING) {
  361. return;
  362. }
  363. // 检查是否碰到墙体(更严格的墙体识别)
  364. const isWall = this.isWallNode(otherCollider.node);
  365. if (isWall) {
  366. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 碰撞到墙体 ${nodeName},切换到待机状态`);
  367. this.state = EnemyState.IDLE;
  368. this.attackTimer = 0; // 立即开始攻击
  369. this.collidedWall = otherCollider.node; // 记录碰撞的墙体
  370. // 停止移动
  371. this.stopRigidBodyMovement();
  372. // 切换到待机动画
  373. this.playIdleAnimation();
  374. }
  375. }
  376. // 检查节点是否为墙体
  377. private isWallNode(node: Node): boolean {
  378. const nodeName = node.name.toLowerCase();
  379. // 检查节点名称是否包含墙体关键词
  380. const wallKeywords = ['wall', 'fence', 'jiguang', '墙', '围栏'];
  381. const isWallByName = wallKeywords.some(keyword => nodeName.includes(keyword));
  382. // 检查节点是否有Wall组件
  383. const hasWallComponent = node.getComponent('Wall') !== null;
  384. return isWallByName || hasWallComponent;
  385. }
  386. // 获取节点路径
  387. getNodePath(node: Node): string {
  388. let path = node.name;
  389. let current = node;
  390. while (current.parent) {
  391. current = current.parent;
  392. path = current.name + '/' + path;
  393. }
  394. return path;
  395. }
  396. // 计算游戏区域中心
  397. private calculateGameAreaCenter() {
  398. const gameArea = find('Canvas/GameLevelUI/GameArea');
  399. if (gameArea) {
  400. this.gameAreaCenter = gameArea.worldPosition;
  401. }
  402. }
  403. /**
  404. * 初始化血条动画组件
  405. */
  406. private initializeHPBarAnimation() {
  407. // 检查是否已经存在血条动画组件,避免重复添加
  408. if (this.hpBarAnimation) {
  409. console.log(`[EnemyInstance] 血条动画组件已存在,跳过初始化`);
  410. return;
  411. }
  412. const hpBar = this.node.getChildByName('HPBar');
  413. if (hpBar) {
  414. // 查找红色和黄色血条节点
  415. const redBarNode = hpBar.getChildByName('RedBar');
  416. const yellowBarNode = hpBar.getChildByName('YellowBar');
  417. if (redBarNode && yellowBarNode) {
  418. // 检查节点是否已经有HPBarAnimation组件
  419. let existingHPBarAnimation = this.node.getComponent(HPBarAnimation);
  420. if (existingHPBarAnimation) {
  421. this.hpBarAnimation = existingHPBarAnimation;
  422. console.log(`[EnemyInstance] 使用已存在的血条动画组件`);
  423. } else {
  424. // 添加血条动画组件
  425. this.hpBarAnimation = this.node.addComponent(HPBarAnimation);
  426. console.log(`[EnemyInstance] 新建血条动画组件`);
  427. }
  428. if (this.hpBarAnimation) {
  429. // 正确设置红色和黄色血条节点引用
  430. this.hpBarAnimation.redBarNode = redBarNode;
  431. this.hpBarAnimation.yellowBarNode = yellowBarNode;
  432. this.hpBarAnimation.hpBarRootNode = hpBar; // 设置HPBar根节点
  433. console.log(`[EnemyInstance] 血条动画组件已初始化`);
  434. }
  435. } else {
  436. console.warn(`[EnemyInstance] HPBar下未找到RedBar或YellowBar节点,RedBar: ${!!redBarNode}, YellowBar: ${!!yellowBarNode}`);
  437. }
  438. } else {
  439. console.warn(`[EnemyInstance] 未找到HPBar节点,无法初始化血条动画`);
  440. }
  441. }
  442. // 更新血量显示
  443. updateHealthDisplay(showBar: boolean = false) {
  444. // 确保血量值在有效范围内
  445. this.health = Math.max(0, Math.min(this.maxHealth, this.health));
  446. const healthProgress = this.maxHealth > 0 ? this.health / this.maxHealth : 0;
  447. console.log(`[EnemyInstance] 更新血量显示: ${this.health}/${this.maxHealth} (${(healthProgress * 100).toFixed(1)}%)`);
  448. // 使用血条动画组件更新血条
  449. if (this.hpBarAnimation) {
  450. this.hpBarAnimation.updateProgress(healthProgress, showBar);
  451. } else {
  452. // 备用方案:直接更新血条
  453. const hpBar = this.node.getChildByName('HPBar');
  454. if (hpBar) {
  455. const progressBar = hpBar.getComponent(ProgressBar);
  456. if (progressBar) {
  457. progressBar.progress = healthProgress;
  458. }
  459. // 根据showBar参数控制血条显示
  460. hpBar.active = showBar;
  461. }
  462. }
  463. // 更新血量数字
  464. const hpLabel = this.node.getChildByName('HPLabel');
  465. if (hpLabel) {
  466. const label = hpLabel.getComponent(Label);
  467. if (label) {
  468. // 显示整数血量值
  469. label.string = Math.ceil(this.health).toString();
  470. }
  471. }
  472. }
  473. // 受到伤害
  474. takeDamage(damage: number, isCritical: boolean = false) {
  475. // 如果已经死亡,不再处理伤害
  476. if (this.state === EnemyState.DEAD) {
  477. return;
  478. }
  479. // 确保伤害值为正数
  480. if (damage <= 0) {
  481. console.warn(`[EnemyInstance] 无效的伤害值: ${damage}`);
  482. return;
  483. }
  484. // 应用防御力减少伤害
  485. const enemyComponent = this.getComponent(EnemyComponent);
  486. const defense = enemyComponent ? enemyComponent.getDefense() : 0;
  487. let finalDamage = Math.max(1, damage - defense); // 至少造成1点伤害
  488. // 检查格挡
  489. if (enemyComponent && enemyComponent.canBlock() && this.tryBlock()) {
  490. finalDamage *= (1 - enemyComponent.getBlockDamageReduction());
  491. this.showBlockEffect();
  492. }
  493. // 计算新的血量,确保不会低于0
  494. const oldHealth = this.health;
  495. const newHealth = Math.max(0, this.health - finalDamage);
  496. const actualHealthLoss = oldHealth - newHealth; // 实际血量损失
  497. this.health = newHealth;
  498. // 检查是否触发狂暴
  499. this.checkRageTrigger();
  500. // 日志显示武器的真实伤害值,而不是血量差值
  501. console.log(`[EnemyInstance] 敌人受到伤害: ${damage} (武器伤害), 防御后伤害: ${finalDamage}, 实际血量损失: ${actualHealthLoss}, 剩余血量: ${this.health}/${this.maxHealth}`);
  502. // 受击音效已移除
  503. // 显示伤害数字动画(在敌人头顶)- 显示防御后的实际伤害
  504. // 优先使用EnemyController节点上的DamageNumberAni组件实例
  505. if (this.controller) {
  506. const damageAni = this.controller.getComponent(DamageNumberAni);
  507. if (damageAni) {
  508. damageAni.showDamageNumber(finalDamage, this.node.worldPosition, isCritical);
  509. } else {
  510. // 如果没有找到组件实例,使用静态方法作为备用
  511. DamageNumberAni.showDamageNumber(finalDamage, this.node.worldPosition, isCritical);
  512. }
  513. } else {
  514. // 如果没有controller引用,使用静态方法
  515. DamageNumberAni.showDamageNumber(finalDamage, this.node.worldPosition, isCritical);
  516. }
  517. // 更新血量显示和动画,受伤时显示血条
  518. this.updateHealthDisplay(true);
  519. // 如果血量低于等于0,销毁敌人
  520. if (this.health <= 0) {
  521. console.log(`[EnemyInstance] 敌人死亡,开始销毁流程`);
  522. this.state = EnemyState.DEAD;
  523. this.spawnCoin();
  524. // 进入死亡流程,禁用碰撞避免重复命中
  525. const enemySprite = this.node.getChildByName('EnemySprite');
  526. if (enemySprite) {
  527. const col = enemySprite.getComponent(Collider2D);
  528. if (col) col.enabled = false;
  529. }
  530. this.playDeathAnimationAndDestroy();
  531. }
  532. }
  533. onDestroy() {
  534. console.log(`[EnemyInstance] onDestroy 被调用,准备通知控制器`);
  535. // 通知控制器 & GameManager
  536. if (this.controller && typeof (this.controller as any).notifyEnemyDead === 'function') {
  537. // 检查控制器是否处于清理状态,避免在清理过程中触发游戏事件
  538. const isClearing = (this.controller as any).isClearing;
  539. if (isClearing) {
  540. console.log(`[EnemyInstance] 控制器处于清理状态,跳过死亡通知`);
  541. return;
  542. }
  543. console.log(`[EnemyInstance] 调用 notifyEnemyDead`);
  544. (this.controller as any).notifyEnemyDead(this.node);
  545. } else {
  546. console.warn(`[EnemyInstance] 无法调用 notifyEnemyDead: controller=${!!this.controller}`);
  547. }
  548. }
  549. update(deltaTime: number) {
  550. // 如果敌人被暂停,则不执行任何更新逻辑
  551. if (this.isPaused) {
  552. return;
  553. }
  554. if (this.state === EnemyState.DRIFTING) {
  555. this.updateDrifting(deltaTime);
  556. // 在漂移状态也检查墙体碰撞
  557. this.checkWallCollisionByDistance();
  558. } else if (this.state === EnemyState.MOVING) {
  559. this.updateMovement(deltaTime);
  560. // 在移动状态检查墙体碰撞
  561. this.checkWallCollisionByDistance();
  562. } else if (this.state === EnemyState.IDLE) {
  563. this.updateIdle(deltaTime);
  564. } else if (this.state === EnemyState.ATTACKING) {
  565. this.updateAttack(deltaTime);
  566. }
  567. // 不再每帧播放攻击动画,避免日志刷屏
  568. }
  569. // 更新漂移逻辑(从生成位置移动到线上)
  570. private updateDrifting(deltaTime: number) {
  571. if (!this.driftTargetPosition) {
  572. // 如果没有漂移目标位置,直接切换到移动状态
  573. this.state = EnemyState.MOVING;
  574. return;
  575. }
  576. const currentWorldPos = this.node.worldPosition.clone();
  577. const targetWorldPos = this.driftTargetPosition.clone();
  578. const dir = targetWorldPos.subtract(currentWorldPos);
  579. const distanceToTarget = dir.length();
  580. // 如果距离目标很近,切换到移动状态
  581. const stopDistance = 5; // 减小停止距离以提高精度
  582. if (distanceToTarget <= stopDistance) {
  583. this.state = EnemyState.MOVING;
  584. // 确保刚体速度为零
  585. this.stopRigidBodyMovement();
  586. return;
  587. }
  588. if (distanceToTarget === 0) return;
  589. dir.normalize();
  590. // 使用代码控制移动,不依赖物理系统
  591. const driftSpeed = Math.min(this.speed * 8, 500); // 限制最大漂移速度为5500
  592. const moveDistance = driftSpeed * deltaTime;
  593. const actualMoveDistance = Math.min(moveDistance, distanceToTarget);
  594. const newWorldPos = currentWorldPos.add(dir.multiplyScalar(actualMoveDistance));
  595. // 直接设置世界坐标
  596. this.node.setWorldPosition(newWorldPos);
  597. // 确保刚体速度为零,避免物理系统干扰
  598. this.stopRigidBodyMovement();
  599. }
  600. // 更新移动逻辑
  601. private updateMovement(deltaTime: number) {
  602. // 根据配置的移动模式执行不同的移动逻辑
  603. switch (this.movementPattern) {
  604. case 'direct':
  605. this.updateDirectMovement(deltaTime);
  606. break;
  607. case 'patrol':
  608. this.updatePatrolMovement(deltaTime);
  609. break;
  610. default:
  611. this.updateDirectMovement(deltaTime);
  612. break;
  613. }
  614. }
  615. // 直线移动模式
  616. private updateDirectMovement(deltaTime: number) {
  617. this.moveTowardsTarget(deltaTime);
  618. }
  619. // 巡逻移动模式
  620. private updatePatrolMovement(deltaTime: number) {
  621. // 更新方向变化计时器
  622. this.changeDirectionTime += deltaTime;
  623. console.log(`[EnemyInstance] 摆动 调用,changeDirectionTime=${this.changeDirectionTime}`);
  624. // 根据巡逻范围决定方向变化
  625. const enemySprite = this.node.getChildByName('EnemySprite');
  626. if (enemySprite && this.controller) {
  627. const currentPos = enemySprite.worldPosition;
  628. const bounds = this.controller.gameBounds;
  629. // 检查是否到达巡逻边界
  630. const leftBound = bounds.left + this.patrolRange;
  631. const rightBound = bounds.right - this.patrolRange;
  632. if (currentPos.x <= leftBound && this.movingDirection < 0) {
  633. this.movingDirection = 1; // 向右
  634. this.changeDirectionTime = 0;
  635. } else if (currentPos.x >= rightBound && this.movingDirection > 0) {
  636. this.movingDirection = -1; // 向左
  637. this.changeDirectionTime = 0;
  638. }
  639. // 随机改变Y目标位置
  640. if (this.changeDirectionTime >= 3 + Math.random() * 2) {
  641. const centerY = (bounds.top + bounds.bottom) / 2;
  642. const range = (bounds.top - bounds.bottom) * 0.4;
  643. this.targetY = centerY + (Math.random() - 0.5) * range;
  644. this.changeDirectionTime = 0;
  645. }
  646. }
  647. this.moveTowardsTarget(deltaTime);
  648. }
  649. // 向目标移动
  650. private moveTowardsTarget(deltaTime: number) {
  651. // 获取当前速度(考虑狂暴加成和速度变化)
  652. const enemyComponent = this.getComponent(EnemyComponent);
  653. let currentSpeed = enemyComponent ? enemyComponent.getCurrentSpeed() : this.speed;
  654. // 应用速度变化配置,限制变化幅度防止过大跳跃
  655. if (this.speedVariation > 0) {
  656. const maxVariation = Math.min(this.speedVariation, currentSpeed * 0.3); // 限制变化不超过当前速度的30%
  657. const variation = (Math.random() - 0.5) * 2 * maxVariation;
  658. currentSpeed = Math.max(currentSpeed + variation, currentSpeed * 0.5); // 确保速度不会过低
  659. }
  660. // 统一使用主节点的世界坐标,与updateDrifting保持一致
  661. const currentPos = this.node.worldPosition.clone();
  662. let dir = new Vec3();
  663. // 水平移动方向
  664. dir.x = this.movingDirection;
  665. // 垂直移动方向 - 向目标Y位置移动
  666. const yDiff = this.targetY - currentPos.y;
  667. if (Math.abs(yDiff) > 10) { // 如果距离目标Y位置超过10像素
  668. dir.y = yDiff > 0 ? 0.5 : -0.5; // 缓慢向目标Y移动
  669. } else {
  670. dir.y = 0;
  671. }
  672. // 如果有具体的目标位置(墙体),优先移动到墙体
  673. if (this.targetPosition) {
  674. const targetDir = new Vec3();
  675. Vec3.subtract(targetDir, this.targetPosition.clone(), currentPos);
  676. if (targetDir.length() > 20) { // 距离墙体还有一定距离时
  677. targetDir.normalize();
  678. dir.x = targetDir.x * 0.7; // 70%朝向墙体
  679. dir.y = targetDir.y * 0.7;
  680. }
  681. } else if (this.targetFence) {
  682. const fencePos = this.targetFence.worldPosition.clone();
  683. const targetDir = new Vec3();
  684. Vec3.subtract(targetDir, fencePos, currentPos);
  685. if (targetDir.length() > 20) {
  686. targetDir.normalize();
  687. dir.x = targetDir.x * 0.7;
  688. dir.y = targetDir.y * 0.7;
  689. }
  690. }
  691. // 归一化方向向量
  692. if (dir.length() > 0) {
  693. dir.normalize();
  694. }
  695. // 应用摆动效果(根据配置)
  696. if (this.moveType === 'sway' && this.swingAmplitude > 0) {
  697. this.swayTime += deltaTime;
  698. const swayAmount = Math.sin(this.swayTime * this.swingFrequency) * this.swingAmplitude;
  699. // 计算垂直于移动方向的摆动
  700. const swayDir = new Vec3(-dir.y, dir.x, 0);
  701. swayDir.multiplyScalar(swayAmount / 100); // 将摆动幅度转换为合适的比例
  702. dir.add(swayDir);
  703. }
  704. // 限制单帧移动距离,防止突然跳跃
  705. const moveDistance = currentSpeed * deltaTime;
  706. const maxMoveDistance = Math.min(15, currentSpeed * 0.1); // 限制单帧最大移动距离
  707. const actualMoveDistance = Math.min(moveDistance, maxMoveDistance);
  708. const moveVector = dir.multiplyScalar(actualMoveDistance);
  709. const newPos = new Vec3();
  710. Vec3.add(newPos, currentPos, moveVector);
  711. // 统一使用主节点的setWorldPosition,与updateDrifting保持一致
  712. this.node.setWorldPosition(newPos);
  713. // 确保刚体速度为零,避免物理系统干扰
  714. this.stopRigidBodyMovement();
  715. }
  716. // 更新攻击逻辑
  717. private updateAttack(deltaTime: number) {
  718. // 获取敌人的攻击范围配置
  719. const enemyComponent = this.getComponent(EnemyComponent);
  720. const attackRange = enemyComponent ? enemyComponent.getAttackRange() : 30;
  721. if (attackRange <= 0) {
  722. // 近战攻击:在攻击状态下停止移动
  723. const enemySprite = this.node.getChildByName('EnemySprite');
  724. if (enemySprite) {
  725. const rigidBody = enemySprite.getComponent(RigidBody2D);
  726. if (rigidBody) {
  727. // 停止物理移动
  728. rigidBody.linearVelocity = new Vec2(0, 0);
  729. }
  730. }
  731. } else {
  732. // 远程攻击:继续移动,但不需要在这里播放行走动画
  733. // 攻击动画会在performRangedAttack中播放,完成后会根据状态切换回行走动画
  734. this.updateMovement(deltaTime);
  735. }
  736. this.attackTimer -= deltaTime;
  737. if (this.attackTimer <= 0) {
  738. // 执行攻击
  739. this.performAttack();
  740. // 重置攻击计时器
  741. this.attackTimer = this.attackInterval;
  742. }
  743. }
  744. // 待机状态更新(停止移动但可以攻击)
  745. private updateIdle(deltaTime: number) {
  746. // 在待机状态下停止移动
  747. const enemySprite = this.node.getChildByName('EnemySprite');
  748. if (enemySprite) {
  749. const rigidBody = enemySprite.getComponent(RigidBody2D);
  750. if (rigidBody) {
  751. // 停止物理移动
  752. rigidBody.linearVelocity = new Vec2(0, 0);
  753. }
  754. }
  755. this.attackTimer -= deltaTime;
  756. if (this.attackTimer <= 0) {
  757. // 执行攻击
  758. this.performAttack();
  759. // 重置攻击计时器
  760. this.attackTimer = this.attackInterval;
  761. }
  762. }
  763. // 执行攻击
  764. private performAttack() {
  765. if (!this.controller) {
  766. return;
  767. }
  768. const enemyComponent = this.getComponent(EnemyComponent);
  769. const attackType = enemyComponent ? enemyComponent.getAttackType() : 'melee';
  770. // 播放攻击音效
  771. EnemyAudio.playAttackSound(this.enemyConfig);
  772. // 根据攻击类型执行不同的攻击逻辑
  773. if (attackType === 'ranged' || attackType === 'projectile' || attackType.includes('projectile')) {
  774. console.log(`[EnemyInstance] 执行远程攻击,攻击类型: ${attackType}`);
  775. this.performRangedAttack();
  776. } else {
  777. // 近战攻击:播放攻击动画,动画结束后造成伤害
  778. console.log(`[EnemyInstance] 执行近战攻击,攻击类型: ${attackType}`);
  779. this.playAttackAnimationWithDamage();
  780. }
  781. }
  782. // 执行远程攻击(投掷)
  783. private performRangedAttack() {
  784. const enemyComponent = this.getComponent(EnemyComponent);
  785. if (!enemyComponent) return;
  786. // 远程攻击也需要播放攻击动画,在动画即将结束时发射抛掷物
  787. this.playRangedAttackAnimationWithProjectile();
  788. }
  789. // 播放远程攻击动画并在动画结束时发射抛掷物
  790. private playRangedAttackAnimationWithProjectile() {
  791. if (!this.skeleton) {
  792. // 如果没有骨骼动画,直接发射抛掷物
  793. this.fireProjectile();
  794. return;
  795. }
  796. const enemyComp = this.getComponent('EnemyComponent') as any;
  797. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  798. const attackName = anims.attack ?? 'attack';
  799. const animation = this.skeleton.findAnimation(attackName);
  800. if (animation) {
  801. // 播放攻击动画(不循环)
  802. this.skeleton.setAnimation(0, attackName, false);
  803. // 动画切换后延迟更新血条位置,确保动画尺寸已生效
  804. this.scheduleOnce(() => {
  805. this.updateHPBarPosition();
  806. }, 0.1);
  807. // 获取动画时长并在动画即将结束时发射抛掷物
  808. const animationDuration = animation.duration;
  809. console.log(`[EnemyInstance] 远程攻击动画时长: ${animationDuration}秒`);
  810. // 在动画播放到90%时发射抛掷物,让抛掷物发射与动画同步
  811. const projectileFireTime = animationDuration * 0.9;
  812. this.scheduleOnce(() => {
  813. this.fireProjectile();
  814. }, projectileFireTime);
  815. // 动画完成后根据当前状态切换动画
  816. this.scheduleOnce(() => {
  817. if (this.state === EnemyState.IDLE) {
  818. // 如果是待机状态,切换回待机动画
  819. this.playIdleAnimation();
  820. } else if (this.state === EnemyState.ATTACKING) {
  821. // 如果还在攻击状态(移动中攻击),切换回行走动画
  822. this.playWalkAnimation();
  823. }
  824. }, animationDuration);
  825. } else {
  826. // 如果找不到攻击动画,直接发射抛掷物
  827. this.fireProjectile();
  828. }
  829. }
  830. // 发射抛掷物
  831. private fireProjectile() {
  832. const enemyComponent = this.getComponent(EnemyComponent);
  833. if (!enemyComponent) return;
  834. const projectileType = enemyComponent.getProjectileType();
  835. const projectileSpeed = enemyComponent.getProjectileSpeed();
  836. const attackDamage = enemyComponent.getDamage();
  837. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 发射投掷物: ${projectileType}, 速度: ${projectileSpeed}, 伤害: ${attackDamage}`);
  838. // 获取EnemyProjectile组件来创建抛掷物
  839. if (this.controller) {
  840. console.log('[EnemyInstance] 找到controller,开始获取EnemyProjectile组件');
  841. const enemyProjectile = this.controller.getComponent('EnemyProjectile') as any;
  842. if (enemyProjectile) {
  843. console.log('[EnemyInstance] 找到EnemyProjectile组件,准备创建抛掷物');
  844. // 计算抛掷物发射方向(朝向目标墙体)
  845. let direction = new Vec3(0, -1, 0); // 默认向下
  846. if (this.collidedWall) {
  847. const currentPos = this.node.worldPosition;
  848. const wallPos = this.collidedWall.worldPosition;
  849. direction = wallPos.clone().subtract(currentPos).normalize();
  850. console.log('[EnemyInstance] 计算抛掷物方向,目标墙体:', this.collidedWall.name, '方向:', direction);
  851. } else {
  852. console.log('[EnemyInstance] 未找到目标墙体,使用默认方向');
  853. }
  854. // 创建抛掷物配置
  855. const projectileConfig = {
  856. damage: attackDamage,
  857. speed: projectileSpeed,
  858. direction: direction,
  859. projectileType: projectileType,
  860. startPosition: this.node.worldPosition.clone()
  861. };
  862. console.log('[EnemyInstance] 抛掷物配置:', projectileConfig);
  863. // 创建抛掷物
  864. const projectileNode = enemyProjectile.createProjectile(projectileConfig);
  865. if (projectileNode) {
  866. console.log(`[EnemyInstance] 成功创建抛掷物,目标方向: ${direction.toString()}`);
  867. } else {
  868. console.error(`[EnemyInstance] 创建抛掷物失败 - 远程敌人攻击无效`);
  869. }
  870. } else {
  871. console.error(`[EnemyInstance] 未找到EnemyProjectile组件 - 远程敌人攻击无效`);
  872. }
  873. } else {
  874. console.error(`[EnemyInstance] 没有controller引用 - 远程敌人攻击无效`);
  875. }
  876. }
  877. // 播放行走动画
  878. private playWalkAnimation() {
  879. if (!this.skeleton) return;
  880. const enemyComp = this.getComponent('EnemyComponent') as any;
  881. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  882. const walkName = anims.walk ?? 'walk';
  883. const idleName = anims.idle ?? 'idle';
  884. if (this.skeleton.findAnimation(walkName)) {
  885. this.skeleton.setAnimation(0, walkName, true);
  886. // 行走音效已移除
  887. } else if (this.skeleton.findAnimation(idleName)) {
  888. this.skeleton.setAnimation(0, idleName, true);
  889. }
  890. // 动画切换后延迟更新血条位置,确保动画尺寸已生效
  891. this.scheduleOnce(() => {
  892. this.updateHPBarPosition();
  893. }, 0.1);
  894. }
  895. // 播放攻击动画
  896. private playAttackAnimation() {
  897. if (!this.skeleton) return;
  898. const enemyComp2 = this.getComponent('EnemyComponent') as any;
  899. const anims2 = enemyComp2?.getAnimations ? enemyComp2.getAnimations() : {};
  900. const attackName = anims2.attack ?? 'attack';
  901. // 移除频繁打印
  902. if (this.skeleton.findAnimation(attackName)) {
  903. this.skeleton.setAnimation(0, attackName, true);
  904. }
  905. // 动画切换后延迟更新血条位置,确保动画尺寸已生效
  906. this.scheduleOnce(() => {
  907. this.updateHPBarPosition();
  908. }, 0.1);
  909. }
  910. // 播放待机动画
  911. private playIdleAnimation() {
  912. if (!this.skeleton) return;
  913. const enemyComp = this.getComponent('EnemyComponent') as any;
  914. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  915. const idleName = anims.idle ?? 'idle';
  916. if (this.skeleton.findAnimation(idleName)) {
  917. this.skeleton.setAnimation(0, idleName, true);
  918. }
  919. // 动画切换后延迟更新血条位置,确保动画尺寸已生效
  920. this.scheduleOnce(() => {
  921. this.updateHPBarPosition();
  922. }, 0.1);
  923. }
  924. // 播放攻击动画并在动画结束时造成伤害
  925. private playAttackAnimationWithDamage() {
  926. if (!this.skeleton) {
  927. // 如果没有骨骼动画,直接造成伤害
  928. this.dealDamageToWall();
  929. return;
  930. }
  931. const enemyComp = this.getComponent('EnemyComponent') as any;
  932. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  933. const attackName = anims.attack ?? 'attack';
  934. const animation = this.skeleton.findAnimation(attackName);
  935. if (animation) {
  936. // 播放攻击动画(不循环)
  937. this.skeleton.setAnimation(0, attackName, false);
  938. // 动画切换后延迟更新血条位置,确保动画尺寸已生效
  939. this.scheduleOnce(() => {
  940. this.updateHPBarPosition();
  941. }, 0.1);
  942. // 获取动画时长并在动画结束时造成伤害
  943. const animationDuration = animation.duration;
  944. console.log(`[EnemyInstance] 攻击动画时长: ${animationDuration}秒`);
  945. // 使用定时器在动画结束时造成伤害
  946. this.scheduleOnce(() => {
  947. this.dealDamageToWall();
  948. // 动画完成后根据当前状态切换动画
  949. if (this.state === EnemyState.IDLE) {
  950. // 如果是待机状态,切换回待机动画
  951. this.playIdleAnimation();
  952. } else {
  953. // 其他状态切换回行走动画
  954. this.playWalkAnimation();
  955. }
  956. }, animationDuration);
  957. } else {
  958. // 如果找不到攻击动画,直接造成伤害
  959. this.dealDamageToWall();
  960. }
  961. }
  962. // 对墙体造成伤害
  963. private dealDamageToWall() {
  964. if (this.controller) {
  965. // 获取当前攻击力(考虑狂暴加成)
  966. const enemyComponent = this.getComponent(EnemyComponent);
  967. const currentAttackPower = enemyComponent ? enemyComponent.getCurrentAttackPower() : this.attackPower;
  968. // 检查是否需要触发画面震动
  969. if (enemyComponent && enemyComponent.getCausesWallShake()) {
  970. const attackType = enemyComponent.getAttackType();
  971. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 攻击墙体,触发画面震动,攻击类型: ${attackType}`);
  972. // 根据攻击类型触发对应的震动效果
  973. ScreenShakeManager.getInstance().playShakeByAttackType(attackType);
  974. }
  975. // 使用统一的事件机制触发墙体伤害
  976. EventBus.getInstance().emit(GameEvents.ENEMY_DAMAGE_WALL, {
  977. damage: currentAttackPower,
  978. source: this.node
  979. });
  980. }
  981. }
  982. private playDeathAnimationAndDestroy() {
  983. console.log(`[EnemyInstance] 开始播放死亡动画并销毁`);
  984. // 播放死亡音效
  985. EnemyAudio.playDeathSound(this.enemyConfig);
  986. if (this.skeleton) {
  987. const enemyComp = this.getComponent('EnemyComponent') as any;
  988. const anims = enemyComp?.getAnimations ? enemyComp.getAnimations() : {};
  989. const deathName = anims.dead ?? 'dead';
  990. if (this.skeleton.findAnimation(deathName)) {
  991. this.skeleton.setAnimation(0, deathName, false);
  992. // 销毁节点在动画完毕后
  993. this.skeleton.setCompleteListener(() => {
  994. this.node.destroy();
  995. });
  996. return;
  997. }
  998. }
  999. this.node.destroy();
  1000. }
  1001. private spawnCoin() {
  1002. const ctrl = this.controller as any; // EnemyController
  1003. if (!ctrl?.coinPrefab) return;
  1004. // 获取配置中的掉落金币数量
  1005. const dropCoinsCount = this.getDropCoins();
  1006. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 掉落 ${dropCoinsCount} 个金币`);
  1007. // 根据配置掉落相应数量的金币
  1008. for (let i = 0; i < dropCoinsCount; i++) {
  1009. const coin = instantiate(ctrl.coinPrefab);
  1010. find('Canvas')!.addChild(coin); // 放到 UI 层
  1011. const pos = new Vec3();
  1012. this.node.getWorldPosition(pos); // 取死亡敌人的世界坐标
  1013. // 如果掉落多个金币,添加一些随机偏移避免重叠
  1014. if (dropCoinsCount > 1) {
  1015. const offsetX = (Math.random() - 0.5) * 40; // 随机X偏移 -20到20
  1016. const offsetY = (Math.random() - 0.5) * 40; // 随机Y偏移 -20到20
  1017. pos.x += offsetX;
  1018. pos.y += offsetY;
  1019. }
  1020. coin.worldPosition = pos; // 金币就在敌人身上出现
  1021. }
  1022. }
  1023. /**
  1024. * 暂停敌人
  1025. */
  1026. public pause(): void {
  1027. this.isPaused = true;
  1028. // 暂停物理系统
  1029. const enemySprite = this.node.getChildByName('EnemySprite');
  1030. if (enemySprite) {
  1031. const rigidBody = enemySprite.getComponent(RigidBody2D);
  1032. if (rigidBody) {
  1033. // 保存当前速度并停止物理移动
  1034. (this as any).savedVelocity = rigidBody.linearVelocity;
  1035. rigidBody.linearVelocity = new Vec2(0, 0);
  1036. }
  1037. }
  1038. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 已暂停`);
  1039. }
  1040. /**
  1041. * 恢复敌人
  1042. */
  1043. public resume(): void {
  1044. this.isPaused = false;
  1045. // 恢复物理系统
  1046. const enemySprite = this.node.getChildByName('EnemySprite');
  1047. if (enemySprite) {
  1048. const rigidBody = enemySprite.getComponent(RigidBody2D);
  1049. if (rigidBody && (this as any).savedVelocity) {
  1050. // 恢复之前保存的速度
  1051. rigidBody.linearVelocity = (this as any).savedVelocity;
  1052. (this as any).savedVelocity = null;
  1053. }
  1054. }
  1055. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 已恢复`);
  1056. }
  1057. /**
  1058. * 检查是否暂停
  1059. */
  1060. public isPausedState(): boolean {
  1061. return this.isPaused;
  1062. }
  1063. /**
  1064. * 获取敌人当前状态
  1065. */
  1066. public getState(): EnemyState {
  1067. return this.state;
  1068. }
  1069. /**
  1070. * 检查敌人是否处于漂移状态
  1071. */
  1072. public isDrifting(): boolean {
  1073. return this.state === EnemyState.DRIFTING;
  1074. }
  1075. /**
  1076. * 重置血条状态(满血并隐藏)
  1077. */
  1078. public resetHealthBar(): void {
  1079. if (this.hpBarAnimation) {
  1080. this.hpBarAnimation.resetToFullAndHide();
  1081. } else {
  1082. // 备用方案:直接隐藏血条
  1083. const hpBar = this.node.getChildByName('HPBar');
  1084. if (hpBar) {
  1085. hpBar.active = false;
  1086. const progressBar = hpBar.getComponent(ProgressBar);
  1087. if (progressBar) {
  1088. progressBar.progress = 1.0;
  1089. }
  1090. }
  1091. }
  1092. }
  1093. /**
  1094. * 尝试格挡攻击
  1095. */
  1096. private tryBlock(): boolean {
  1097. const enemyComponent = this.getComponent(EnemyComponent);
  1098. if (!enemyComponent) return false;
  1099. const blockChance = enemyComponent.getBlockChance();
  1100. // 将百分比值转换为0-1范围(例如:30.0 -> 0.3)
  1101. const blockChanceNormalized = blockChance / 100.0;
  1102. return Math.random() < blockChanceNormalized;
  1103. }
  1104. /**
  1105. * 基于距离检查墙体碰撞和攻击范围
  1106. */
  1107. private checkWallCollisionByDistance(): void {
  1108. if (this.state === EnemyState.ATTACKING || this.state === EnemyState.IDLE) {
  1109. return; // 已经在攻击状态或待机状态,不需要再检查
  1110. }
  1111. const enemySprite = this.node.getChildByName('EnemySprite');
  1112. if (!enemySprite) return;
  1113. const currentPos = enemySprite.worldPosition;
  1114. // 获取敌人的攻击范围配置
  1115. const enemyComponent = this.getComponent(EnemyComponent);
  1116. const attackRange = enemyComponent ? enemyComponent.getAttackRange() : 30;
  1117. // 根据攻击范围确定检测距离和攻击类型
  1118. let detectionDistance: number;
  1119. let isRangedAttack: boolean;
  1120. if (attackRange <= 0) {
  1121. // 近战攻击:需要接近墙体
  1122. detectionDistance = 30;
  1123. isRangedAttack = false;
  1124. } else {
  1125. // 远程攻击:在攻击范围内就开始攻击
  1126. detectionDistance = attackRange;
  1127. isRangedAttack = true;
  1128. }
  1129. // 获取所有墙体节点进行距离检测
  1130. const wallNodes = this.getAllWallNodes();
  1131. for (const wallNode of wallNodes) {
  1132. const wallPos = wallNode.worldPosition;
  1133. const distance = Vec3.distance(currentPos, wallPos);
  1134. if (distance <= detectionDistance) {
  1135. const attackTypeStr = isRangedAttack ? '远程攻击' : '近战攻击';
  1136. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 进入${attackTypeStr}范围,距离墙体 ${wallNode.name}: ${distance.toFixed(2)},攻击范围: ${attackRange}`);
  1137. if (isRangedAttack) {
  1138. // 远程攻击:切换到攻击状态,继续移动并发射抛掷物
  1139. this.state = EnemyState.ATTACKING;
  1140. this.attackTimer = 0; // 立即开始攻击
  1141. this.collidedWall = wallNode; // 记录目标墙体
  1142. // 远程攻击时继续播放walk动画,不停止移动
  1143. this.playWalkAnimation();
  1144. console.log(`[EnemyInstance] 远程敌人 ${this.getEnemyName()} 进入攻击状态,继续移动并播放walk动画`);
  1145. } else {
  1146. // 近战攻击:切换到待机状态,停止移动
  1147. this.state = EnemyState.IDLE;
  1148. this.attackTimer = 0; // 立即开始攻击
  1149. this.collidedWall = wallNode; // 记录碰撞的墙体
  1150. // 停止移动
  1151. this.stopRigidBodyMovement();
  1152. // 切换到待机动画
  1153. this.playIdleAnimation();
  1154. }
  1155. return; // 找到一个墙体就停止检查
  1156. }
  1157. }
  1158. }
  1159. /**
  1160. * 获取所有墙体节点
  1161. */
  1162. private getAllWallNodes(): Node[] {
  1163. const wallNodes: Node[] = [];
  1164. // 通过EnemyController获取墙体节点
  1165. if (this.controller) {
  1166. if (this.controller.topFenceNode) {
  1167. wallNodes.push(this.controller.topFenceNode);
  1168. }
  1169. if (this.controller.bottomFenceNode) {
  1170. wallNodes.push(this.controller.bottomFenceNode);
  1171. }
  1172. }
  1173. // 备用方案:在场景中查找墙体节点
  1174. if (wallNodes.length === 0) {
  1175. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1176. if (gameArea) {
  1177. for (let i = 0; i < gameArea.children.length; i++) {
  1178. const child = gameArea.children[i];
  1179. if (this.isWallNode(child)) {
  1180. wallNodes.push(child);
  1181. }
  1182. }
  1183. }
  1184. }
  1185. return wallNodes;
  1186. }
  1187. /**
  1188. * 停止刚体移动,确保物理系统不干扰代码控制的移动
  1189. */
  1190. private stopRigidBodyMovement(): void {
  1191. const enemySprite = this.node.getChildByName('EnemySprite');
  1192. if (enemySprite) {
  1193. const rigidBody = enemySprite.getComponent(RigidBody2D);
  1194. if (rigidBody) {
  1195. rigidBody.linearVelocity = new Vec2(0, 0);
  1196. }
  1197. }
  1198. }
  1199. /**
  1200. * 显示格挡效果
  1201. */
  1202. private showBlockEffect(): void {
  1203. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 格挡了攻击`);
  1204. // 显示"格挡"文字效果
  1205. this.showBlockText();
  1206. }
  1207. /**
  1208. * 显示格挡文字
  1209. */
  1210. private showBlockText(): void {
  1211. // 使用DamageNumberAni组件来显示格挡文字,就像显示伤害数字一样
  1212. if (this.controller) {
  1213. const damageAni = this.controller.getComponent(DamageNumberAni);
  1214. if (damageAni) {
  1215. damageAni.showBlockText(this.node.worldPosition);
  1216. } else {
  1217. console.warn('[EnemyInstance] 未找到DamageNumberAni组件,无法显示格挡文字');
  1218. }
  1219. } else {
  1220. console.warn('[EnemyInstance] 未找到controller引用,无法显示格挡文字');
  1221. }
  1222. }
  1223. /**
  1224. * 检查是否触发狂暴状态
  1225. */
  1226. private checkRageTrigger(): void {
  1227. const enemyComponent = this.getComponent(EnemyComponent);
  1228. if (!enemyComponent) return;
  1229. const healthPercent = this.health / this.maxHealth;
  1230. const rageTriggerThreshold = enemyComponent.getRageTriggerThreshold();
  1231. if (healthPercent <= rageTriggerThreshold && !enemyComponent.isInRage()) {
  1232. enemyComponent.triggerRage();
  1233. console.log(`[EnemyInstance] 敌人 ${this.getEnemyName()} 进入狂暴状态`);
  1234. }
  1235. }
  1236. }