EnemyInstance.ts 34 KB

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