EnemyInstance.ts 35 KB

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