EnemyInstance.ts 69 KB

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