BulletHitEffect.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. import { _decorator, Component, Node, Vec3, find, instantiate, Prefab, UITransform, resources, sp, CircleCollider2D, Contact2DType, Collider2D, IPhysics2DContact, Animation } from 'cc';
  2. import { BulletTrajectory } from './BulletTrajectory';
  3. import { HitEffectConfig } from '../../Core/ConfigManager';
  4. import { PersistentSkillManager } from '../../FourUI/SkillSystem/PersistentSkillManager';
  5. import { BurnEffect } from './BurnEffect';
  6. import { GroundBurnArea } from './GroundBurnArea';
  7. import { GroundBurnAreaManager } from './GroundBurnAreaManager';
  8. import { WeaponBullet } from '../WeaponBullet';
  9. import EventBus, { GameEvents } from '../../Core/EventBus';
  10. import { Audio } from '../../AudioManager/AudioManager';
  11. import { BundleLoader } from '../../Core/BundleLoader';
  12. const { ccclass, property } = _decorator;
  13. /**
  14. * 命中效果控制器
  15. * 负责处理可叠加的命中效果
  16. */
  17. // 接口定义已移至ConfigManager.ts中的HitEffectConfig
  18. export interface HitResult {
  19. shouldDestroy: boolean; // 是否应该销毁子弹
  20. shouldContinue: boolean; // 是否应该继续飞行
  21. shouldRicochet: boolean; // 是否应该弹射
  22. damageDealt: number; // 造成的伤害
  23. }
  24. @ccclass('BulletHitEffect')
  25. export class BulletHitEffect extends Component {
  26. private hitEffects: HitEffectConfig[] = [];
  27. private hitCount: number = 0;
  28. private pierceCount: number = 0;
  29. private ricochetCount: number = 0;
  30. private activeBurnAreas: Node[] = [];
  31. // 检测范围相关
  32. private detectionCollider: CircleCollider2D | null = null;
  33. private detectedEnemies: Set<Node> = new Set();
  34. // 锯齿草子弹状态管理
  35. private hasFirstHit: boolean = false; // 是否已经首次击中敌人
  36. private currentTargetEnemy: Node | null = null; // 当前击中的目标敌人
  37. // 默认特效路径(从WeaponBullet传入)
  38. private defaultHitEffectPath: string = '';
  39. private defaultTrailEffectPath: string = '';
  40. private defaultBurnEffectPath: string = '';
  41. public setDefaultEffects(hit: string | null, trail?: string | null, burn?: string | null) {
  42. if (hit) this.defaultHitEffectPath = hit;
  43. if (trail) this.defaultTrailEffectPath = trail;
  44. if (burn) this.defaultBurnEffectPath = burn;
  45. }
  46. /**
  47. * 初始化命中效果
  48. */
  49. public init(effects: HitEffectConfig[]) {
  50. // 按优先级排序
  51. this.hitEffects = [...effects].sort((a, b) => a.priority - b.priority);
  52. // 重置锯齿草状态
  53. this.resetSawGrassState();
  54. // 检查是否有手动添加的检测范围碰撞器
  55. this.setupDetectionColliderEvents();
  56. }
  57. /**
  58. * 处理命中事件
  59. */
  60. public processHit(hitNode: Node, contactPos: Vec3): HitResult {
  61. // 检查是否是弹射后的命中
  62. const isRicochetHit = this.ricochetCount > 0;
  63. const hitType = isRicochetHit ? '弹射命中' : '直接命中';
  64. // 锯齿草子弹首次击中逻辑
  65. const weaponBullet = this.getComponent(WeaponBullet);
  66. const weaponInfo = weaponBullet ? weaponBullet.getWeaponInfo() : null;
  67. const weaponId = weaponInfo ? weaponInfo.getWeaponId() : null;
  68. if (weaponId === 'saw_grass' && !this.hasFirstHit && this.isEnemyNode(hitNode)) {
  69. this.hasFirstHit = true;
  70. this.currentTargetEnemy = hitNode;
  71. }
  72. this.hitCount++;
  73. const result: HitResult = {
  74. shouldDestroy: false,
  75. shouldContinue: false,
  76. shouldRicochet: false,
  77. damageDealt: 0
  78. };
  79. // 按优先级处理所有效果
  80. for (const effect of this.hitEffects) {
  81. const effectResult = this.processEffect(effect, hitNode, contactPos);
  82. // 累积伤害
  83. result.damageDealt += effectResult.damageDealt;
  84. // 处理控制逻辑(OR逻辑,任何一个效果要求的行为都会执行)
  85. if (effectResult.shouldDestroy) result.shouldDestroy = true;
  86. if (effectResult.shouldContinue) result.shouldContinue = true;
  87. if (effectResult.shouldRicochet) result.shouldRicochet = true;
  88. }
  89. // 逻辑优先级:销毁 > 弹射 > 继续
  90. if (result.shouldDestroy) {
  91. result.shouldContinue = false;
  92. result.shouldRicochet = false;
  93. } else if (result.shouldRicochet) {
  94. result.shouldContinue = false;
  95. }
  96. return result;
  97. }
  98. /**
  99. * 处理单个效果
  100. */
  101. private processEffect(effect: HitEffectConfig, hitNode: Node, contactPos: Vec3): HitResult {
  102. const result: HitResult = {
  103. shouldDestroy: false,
  104. shouldContinue: false,
  105. shouldRicochet: false,
  106. damageDealt: 0
  107. };
  108. switch (effect.type) {
  109. case 'normal_damage':
  110. result.damageDealt = this.processNormalDamage(effect, hitNode);
  111. result.shouldDestroy = true;
  112. break;
  113. case 'pierce_damage':
  114. result.damageDealt = this.processPierceDamage(effect, hitNode);
  115. break;
  116. case 'explosion':
  117. result.damageDealt = this.processExplosion(effect, contactPos);
  118. result.shouldDestroy = true;
  119. break;
  120. case 'ground_burn':
  121. this.processGroundBurn(effect, hitNode);
  122. break;
  123. case 'ricochet_damage':
  124. // 先判断是否可以弹射(在递增ricochetCount之前)
  125. const canRicochet = this.ricochetCount < (effect.ricochetCount || 0);
  126. result.damageDealt = this.processRicochetDamage(effect, hitNode);
  127. result.shouldRicochet = canRicochet;
  128. break;
  129. }
  130. return result;
  131. }
  132. /**
  133. * 处理普通伤害
  134. */
  135. private processNormalDamage(effect: any, hitNode: Node): number {
  136. // 使用WeaponBullet的最终伤害值而不是配置中的基础伤害
  137. const weaponBullet = this.getComponent(WeaponBullet);
  138. const damage = weaponBullet ? weaponBullet.getFinalDamage() : (effect.damage || 0);
  139. this.damageEnemy(hitNode, damage);
  140. this.spawnHitEffect(hitNode.worldPosition);
  141. return damage;
  142. }
  143. /**
  144. * 处理穿透伤害
  145. */
  146. private processPierceDamage(effect: HitEffectConfig, hitNode: Node): number {
  147. // 使用WeaponBullet的最终伤害值而不是配置中的基础伤害
  148. const weaponBullet = this.getComponent(WeaponBullet);
  149. const damage = weaponBullet ? weaponBullet.getFinalDamage() : (effect.damage || 0);
  150. this.damageEnemy(hitNode, damage);
  151. this.spawnHitEffect(hitNode.worldPosition);
  152. this.pierceCount++;
  153. return damage;
  154. }
  155. /**
  156. * 处理爆炸效果
  157. */
  158. private processExplosion(effect: HitEffectConfig, position: Vec3): number {
  159. // 使用WeaponBullet的最终伤害值而不是配置中的基础伤害
  160. const weaponBullet = this.getComponent(WeaponBullet);
  161. const explosionDamage = weaponBullet ? weaponBullet.getFinalDamage() : (effect.damage || 0);
  162. const scheduleExplosion = () => {
  163. // 播放爆炸音效
  164. this.playAttackSound();
  165. // 生成爆炸特效
  166. this.spawnExplosionEffect(position);
  167. // 对范围内敌人造成伤害
  168. const damage = this.damageEnemiesInRadius(position, effect.radius, explosionDamage);
  169. return damage;
  170. };
  171. // 立即爆炸,不使用任何延迟
  172. return scheduleExplosion();
  173. }
  174. /**
  175. * 处理地面燃烧区域效果
  176. */
  177. private processGroundBurn(effect: HitEffectConfig, hitNode: Node) {
  178. // 获取地面燃烧区域管理器
  179. const burnAreaManager = GroundBurnAreaManager.getInstance();
  180. if (!burnAreaManager) {
  181. console.error('[BulletHitEffect] 无法获取GroundBurnAreaManager实例');
  182. return;
  183. }
  184. // 获取子弹的世界位置作为燃烧区域中心
  185. const burnPosition = this.node.worldPosition.clone();
  186. // 如果命中的是敌人,使用敌人的位置
  187. if (this.isEnemyNode(hitNode)) {
  188. burnPosition.set(hitNode.worldPosition);
  189. }
  190. try {
  191. // 获取武器子弹组件
  192. const weaponBullet = this.getComponent(WeaponBullet);
  193. // 通过管理器创建燃烧区域
  194. const burnAreaNode = burnAreaManager.createGroundBurnArea(
  195. burnPosition,
  196. effect,
  197. weaponBullet,
  198. this.defaultBurnEffectPath || this.defaultTrailEffectPath
  199. );
  200. if (burnAreaNode) {
  201. // 将燃烧区域添加到活跃列表中
  202. this.activeBurnAreas.push(burnAreaNode);
  203. }
  204. } catch (error) {
  205. console.error('[BulletHitEffect] 通过管理器创建地面燃烧区域失败:', error);
  206. }
  207. }
  208. /**
  209. * 处理弹射伤害
  210. */
  211. private processRicochetDamage(effect: HitEffectConfig, hitNode: Node): number {
  212. // 使用WeaponBullet的最终伤害值而不是配置中的基础伤害
  213. const weaponBullet = this.getComponent(WeaponBullet);
  214. const damage = weaponBullet ? weaponBullet.getFinalDamage() : (effect.damage || 0);
  215. this.damageEnemy(hitNode, damage);
  216. // 检查是否还能继续弹射
  217. if (this.ricochetCount < effect.ricochetCount) {
  218. this.ricochetCount++;
  219. // 计算弹射方向
  220. this.calculateRicochetDirection(effect.ricochetAngle);
  221. } else {
  222. //console.log(`[BulletHitEffect] 弹射次数已达上限,不再弹射`);
  223. }
  224. return damage;
  225. }
  226. /**
  227. * 计算弹射方向
  228. */
  229. private calculateRicochetDirection(maxAngle: number) {
  230. const trajectory = this.getComponent(BulletTrajectory);
  231. if (!trajectory) return;
  232. // 获取武器子弹组件来确定检测范围
  233. const weaponBullet = this.getComponent(WeaponBullet);
  234. const weaponInfo = weaponBullet ? weaponBullet.getWeaponInfo() : null;
  235. const weaponId = weaponInfo ? weaponInfo.getWeaponId() : null;
  236. const detectionRange = weaponId ? this.getDetectionRange(weaponId) : 500;
  237. let nearestEnemy: Node | null = null;
  238. // 锯齿草武器使用专门的CircleCollider2D实时追踪逻辑
  239. if (weaponId === 'saw_grass') {
  240. nearestEnemy = this.findNearestEnemyForSawGrass(detectionRange);
  241. } else {
  242. // 其他武器使用原有的实时计算方法
  243. nearestEnemy = this.findNearestEnemy(detectionRange);
  244. }
  245. let newDirection: Vec3;
  246. if (nearestEnemy) {
  247. // 如果找到敌人,计算朝向敌人的方向
  248. const bulletPos = this.node.worldPosition;
  249. const enemyPos = nearestEnemy.worldPosition;
  250. // 计算基础方向(朝向敌人)
  251. const baseDirection = enemyPos.clone().subtract(bulletPos).normalize();
  252. // 添加随机偏移角度,让弹射不那么精确
  253. const angleRad = (Math.random() - 0.5) * maxAngle * Math.PI / 180;
  254. const cos = Math.cos(angleRad);
  255. const sin = Math.sin(angleRad);
  256. // 应用旋转偏移
  257. newDirection = new Vec3(
  258. baseDirection.x * cos - baseDirection.y * sin,
  259. baseDirection.x * sin + baseDirection.y * cos,
  260. 0
  261. ).normalize();
  262. const weaponType = weaponId === 'saw_grass' ? '锯齿草CircleCollider2D' : '实时计算';
  263. } else {
  264. // 如果没有找到敌人,使用随机方向(保持原有逻辑)
  265. const currentVel = trajectory.getCurrentVelocity();
  266. const angleRad = (Math.random() - 0.5) * maxAngle * Math.PI / 180;
  267. const cos = Math.cos(angleRad);
  268. const sin = Math.sin(angleRad);
  269. newDirection = new Vec3(
  270. currentVel.x * cos - currentVel.y * sin,
  271. currentVel.x * sin + currentVel.y * cos,
  272. 0
  273. ).normalize();
  274. const weaponType = weaponId === 'saw_grass' ? '锯齿草CircleCollider2D' : '实时计算';
  275. }
  276. // 使用弹道组件的changeDirection方法
  277. trajectory.changeDirection(newDirection);
  278. }
  279. /**
  280. * 对单个敌人造成伤害
  281. */
  282. private damageEnemy(enemyNode: Node, damage: number) {
  283. if (!this.isEnemyNode(enemyNode)) return;
  284. // 检查敌人是否处于漂移状态,如果是则跳过伤害
  285. const enemyInstance = enemyNode.getComponent('EnemyInstance') as any;
  286. if (enemyInstance && enemyInstance.isDrifting()) {
  287. console.log(`[BulletHitEffect] 敌人 ${enemyNode.name} 正在漂移中,跳过伤害处理`);
  288. return; // 漂移状态下不受到伤害
  289. }
  290. // 播放攻击音效
  291. this.playAttackSound();
  292. // 计算暴击伤害和暴击状态
  293. const damageResult = this.calculateCriticalDamage(damage);
  294. // 使用applyDamageToEnemy方法,通过EventBus发送伤害事件
  295. this.applyDamageToEnemy(enemyNode, damageResult.damage, damageResult.isCritical);
  296. }
  297. /**
  298. * 计算暴击伤害
  299. */
  300. private calculateCriticalDamage(baseDamage: number): { damage: number, isCritical: boolean } {
  301. // 获取武器子弹组件来计算暴击
  302. const weaponBullet = this.getComponent(WeaponBullet);
  303. if (!weaponBullet) {
  304. // 如果没有WeaponBullet组件,使用基础暴击率0%
  305. const critChance = 0;
  306. const isCritical = Math.random() < critChance;
  307. if (isCritical) {
  308. // 暴击伤害 = 基础伤害 × (1 + 暴击伤害倍率),默认暴击倍率100%
  309. const critDamage = Math.round(baseDamage * (1 + 1.0)); // 四舍五入为整数
  310. this.showCriticalHitEffect();
  311. return { damage: critDamage, isCritical: true };
  312. }
  313. return { damage: baseDamage, isCritical: false };
  314. }
  315. // 获取暴击率
  316. const critChance = weaponBullet.getCritChance();
  317. // 检查是否触发暴击
  318. const isCritical = Math.random() < critChance;
  319. if (isCritical) {
  320. // 获取暴击伤害倍率(从技能系统)
  321. const critDamageMultiplier = this.getCritDamageMultiplier();
  322. // 暴击伤害 = 基础伤害 × (1 + 暴击伤害倍率)
  323. const critDamage = Math.round(baseDamage * (1 + critDamageMultiplier)); // 四舍五入为整数
  324. // 显示暴击特效
  325. this.showCriticalHitEffect();
  326. return { damage: critDamage, isCritical: true };
  327. }
  328. return { damage: baseDamage, isCritical: false };
  329. }
  330. /**
  331. * 获取暴击伤害倍率
  332. */
  333. private getCritDamageMultiplier(): number {
  334. // 从局外技能系统获取暴击伤害加成
  335. const persistentSkillManager = PersistentSkillManager.getInstance();
  336. if (persistentSkillManager) {
  337. const bonuses = persistentSkillManager.getSkillBonuses();
  338. // critDamageBonus是百分比值,需要转换为倍率
  339. // 暴击伤害倍率 = 基础100% + 技能加成百分比
  340. return 1.0 + (bonuses.critDamageBonus || 0) / 100;
  341. }
  342. // 默认暴击倍率100%(即2倍伤害)
  343. return 1.0;
  344. }
  345. /**
  346. * 播放攻击音效
  347. */
  348. private playAttackSound() {
  349. try {
  350. // 获取武器子弹组件
  351. const weaponBullet = this.getComponent(WeaponBullet);
  352. if (!weaponBullet) {
  353. console.log('[BulletHitEffect] 未找到WeaponBullet组件,无法播放攻击音效');
  354. return;
  355. }
  356. // 获取武器配置
  357. const weaponConfig = weaponBullet.getWeaponConfig();
  358. if (!weaponConfig || !weaponConfig.visualConfig || !weaponConfig.visualConfig.attackSound) {
  359. console.log('[BulletHitEffect] 武器配置中未找到attackSound,跳过音效播放');
  360. return;
  361. }
  362. // 播放攻击音效
  363. const attackSoundPath = weaponConfig.visualConfig.attackSound;
  364. Audio.playWeaponSound(attackSoundPath);
  365. } catch (error) {
  366. console.error('[BulletHitEffect] 播放攻击音效时出错:', error);
  367. }
  368. }
  369. /**
  370. * 显示暴击特效
  371. */
  372. private showCriticalHitEffect() {
  373. // 这里可以添加暴击特效,比如特殊的粒子效果或音效
  374. // 暂时只在控制台输出,后续可以扩展
  375. console.log('[BulletHitEffect] 暴击特效触发!');
  376. }
  377. /**
  378. * 对范围内敌人造成伤害
  379. */
  380. private damageEnemiesInRadius(center: Vec3, radius: number, damage: number): number {
  381. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  382. if (!enemyContainer) return 0;
  383. let totalDamage = 0;
  384. const enemies = enemyContainer.children.filter(child =>
  385. child.active && this.isEnemyNode(child)
  386. );
  387. // 对于持续伤害(如地面灼烧),直接使用传入的伤害值
  388. // 对于爆炸伤害,使用WeaponBullet的最终伤害值
  389. const baseDamage = damage;
  390. console.log(`[BulletHitEffect] 范围伤害 - 中心位置: (${center.x.toFixed(1)}, ${center.y.toFixed(1)}), 半径: ${radius}, 基础伤害: ${baseDamage}`);
  391. for (const enemy of enemies) {
  392. const distance = Vec3.distance(center, enemy.worldPosition);
  393. if (distance <= radius) {
  394. // 检查敌人是否处于漂移状态,如果是则跳过范围伤害
  395. const enemyInstance = enemy.getComponent('EnemyInstance') as any;
  396. if (enemyInstance && enemyInstance.isDrifting()) {
  397. console.log(`[BulletHitEffect] 敌人 ${enemy.name} 正在漂移中,跳过范围伤害`);
  398. continue; // 漂移状态下不受到范围伤害
  399. }
  400. // 每个敌人独立计算暴击
  401. const damageResult = this.calculateCriticalDamage(baseDamage);
  402. console.log(`[BulletHitEffect] 敌人受到范围伤害 - 距离: ${distance.toFixed(1)}, 伤害: ${damageResult.damage}, 暴击: ${damageResult.isCritical}`);
  403. // 直接处理伤害,避免重复计算暴击
  404. this.applyDamageToEnemy(enemy, damageResult.damage, damageResult.isCritical);
  405. totalDamage += damageResult.damage;
  406. }
  407. }
  408. return totalDamage;
  409. }
  410. /**
  411. * 直接对敌人应用伤害(不进行暴击计算)
  412. */
  413. private applyDamageToEnemy(enemyNode: Node, damage: number, isCritical: boolean = false) {
  414. console.log(`[BulletHitEffect] 通过EventBus发送伤害事件: ${damage}, 暴击: ${isCritical}, 敌人节点: ${enemyNode.name}`);
  415. if (!this.isEnemyNode(enemyNode)) {
  416. console.log(`[BulletHitEffect] 节点不是敌人,跳过伤害`);
  417. return;
  418. }
  419. // 通过EventBus发送伤害事件
  420. const eventBus = EventBus.getInstance();
  421. const damageData = {
  422. enemyNode: enemyNode,
  423. damage: damage,
  424. isCritical: isCritical,
  425. source: 'BulletHitEffect'
  426. };
  427. console.log(`[BulletHitEffect] 发送APPLY_DAMAGE_TO_ENEMY事件`, damageData);
  428. eventBus.emit(GameEvents.APPLY_DAMAGE_TO_ENEMY, damageData);
  429. }
  430. /**
  431. * 判断是否为敌人节点
  432. */
  433. private isEnemyNode(node: Node): boolean {
  434. if (!node || !node.isValid) {
  435. return false;
  436. }
  437. // 检查是否为EnemySprite子节点
  438. if (node.name === 'EnemySprite' && node.parent) {
  439. return node.parent.getComponent('EnemyInstance') !== null;
  440. }
  441. // 兼容旧的敌人检测逻辑
  442. const name = node.name.toLowerCase();
  443. return name.includes('enemy') ||
  444. name.includes('敌人');
  445. }
  446. /**
  447. * 获取武器的敌人检测范围
  448. */
  449. private getDetectionRange(weaponId: string): number {
  450. // 根据武器类型设置不同的检测范围
  451. const detectionRanges: { [key: string]: number } = {
  452. 'saw_grass': 500, // 锯齿草:500范围智能弹射
  453. 'sharp_carrot': 300, // 尖胡萝卜:较短范围
  454. 'pea_shooter': 200, // 毛豆射手:基础范围
  455. // 可以根据需要添加更多武器的检测范围
  456. };
  457. return detectionRanges[weaponId] || 300; // 默认300范围
  458. }
  459. /**
  460. * 寻找最近的敌人(在指定范围内)
  461. */
  462. /**
  463. * 锯齿草武器专用的敌人查找方法 - 基于CircleCollider2D检测并实时追踪
  464. */
  465. private findNearestEnemyForSawGrass(maxRange: number = 500): Node | null {
  466. // 如果还没有首次击中敌人,不使用CircleCollider检测到的敌人
  467. if (!this.hasFirstHit) {
  468. console.log(`⏳ [锯齿草弹射] 尚未首次击中敌人,暂不启用CircleCollider追踪`);
  469. return null;
  470. }
  471. // 清理无效的敌人节点
  472. const invalidEnemies = new Set<Node>();
  473. for (const enemy of this.detectedEnemies) {
  474. if (!enemy || !enemy.isValid || !enemy.active) {
  475. invalidEnemies.add(enemy);
  476. }
  477. }
  478. // 移除无效敌人
  479. for (const invalidEnemy of invalidEnemies) {
  480. this.detectedEnemies.delete(invalidEnemy);
  481. }
  482. if (this.detectedEnemies.size === 0) {
  483. return null;
  484. }
  485. const currentPos = this.node.worldPosition;
  486. let nearestEnemy: Node | null = null;
  487. let nearestDistance = Infinity;
  488. // 实时计算每个检测到敌人的当前位置,排除当前目标敌人
  489. for (const enemy of this.detectedEnemies) {
  490. if (enemy && enemy.isValid && enemy.active) {
  491. // 排除当前击中的目标敌人
  492. if (this.currentTargetEnemy && enemy === this.currentTargetEnemy) {
  493. continue;
  494. }
  495. // 获取敌人的实时位置
  496. const enemyCurrentPos = enemy.worldPosition;
  497. const distance = Vec3.distance(currentPos, enemyCurrentPos);
  498. // 检查是否在范围内且是最近的
  499. if (distance <= maxRange && distance < nearestDistance) {
  500. nearestDistance = distance;
  501. nearestEnemy = enemy;
  502. }
  503. }
  504. }
  505. if (nearestEnemy) {
  506. } else {
  507. console.log(`❌ [锯齿草弹射] 检测到的敌人都超出范围或无效,或都是当前目标敌人`);
  508. }
  509. return nearestEnemy;
  510. }
  511. /**
  512. * 通用的敌人查找方法 - 用于非锯齿草武器
  513. */
  514. private findNearestEnemy(maxRange: number = 500): Node | null {
  515. // 回退到原有的实时计算方法(用于非锯齿草武器)
  516. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  517. if (!enemyContainer) return null;
  518. const enemies = enemyContainer.children.filter(child => {
  519. if (!child.active) return false;
  520. const nameLower = child.name.toLowerCase();
  521. if (nameLower.includes('enemy') || nameLower.includes('敌人')) return true;
  522. if (child.getComponent('EnemyInstance')) return true;
  523. return false;
  524. });
  525. if (enemies.length === 0) return null;
  526. let nearest: Node = null;
  527. let nearestDist = Infinity;
  528. const bulletPos = this.node.worldPosition;
  529. for (const enemy of enemies) {
  530. const dist = Vec3.distance(bulletPos, enemy.worldPosition);
  531. // 只考虑在检测范围内的敌人
  532. if (dist <= maxRange && dist < nearestDist) {
  533. nearestDist = dist;
  534. nearest = enemy;
  535. }
  536. }
  537. return nearest;
  538. }
  539. /**
  540. * 生成爆炸特效
  541. */
  542. private spawnExplosionEffect(position: Vec3) {
  543. const path = this.defaultHitEffectPath || 'Animation/WeaponTx/tx0004/tx0004';
  544. this.spawnEffect(path, position, false);
  545. }
  546. /**
  547. * 生成灼烧特效
  548. */
  549. private spawnBurnEffect(parent: Node) {
  550. const path = this.defaultBurnEffectPath || this.defaultTrailEffectPath || 'Animation/WeaponTx/tx0006/tx0006';
  551. // 使用回调函数处理异步创建的特效节点
  552. this.spawnEffect(path, new Vec3(), true, parent, (effectNode) => {
  553. // 将特效节点传递给 BurnEffect 组件,以便在停止时清理
  554. const burnEffect = parent.getComponent(BurnEffect);
  555. if (burnEffect && effectNode) {
  556. burnEffect.setBurnEffectNode(effectNode);
  557. }
  558. });
  559. }
  560. /**
  561. * 生成地面燃烧特效
  562. */
  563. private spawnGroundBurnEffect(parent: Node) {
  564. const path = this.defaultBurnEffectPath || this.defaultTrailEffectPath || 'Animation/WeaponTx/tx0006/tx0006';
  565. // 使用回调函数处理异步创建的特效节点
  566. this.spawnEffect(path, new Vec3(), true, parent, (effectNode) => {
  567. // 将特效节点传递给 GroundBurnArea 组件,以便在停止时清理
  568. const groundBurnArea = parent.getComponent(GroundBurnArea);
  569. if (groundBurnArea && effectNode) {
  570. groundBurnArea.setBurnEffectNode(effectNode);
  571. }
  572. });
  573. }
  574. /**
  575. * 生成特效
  576. */
  577. private spawnEffect(path: string, worldPos: Vec3, loop = false, parent?: Node, onCreated?: (effectNode: Node) => void): void {
  578. if (!path) return;
  579. // 使用BundleLoader加载Animation Bundle中的特效资源
  580. // 转换路径格式,去除"Animation/"前缀
  581. const bundlePath = path.replace(/^Animation\//, '');
  582. const bundleLoader = BundleLoader.getInstance();
  583. // 使用loadSkeletonData加载骨骼动画资源,就像敌人动画那样
  584. BundleLoader.loadSkeletonData(bundlePath).then((skData) => {
  585. if (!skData) {
  586. console.warn('加载特效失败: 资源为空', path);
  587. return;
  588. }
  589. // 创建特效节点
  590. const effectNode = new Node('Effect');
  591. const skeletonComp: sp.Skeleton = effectNode.addComponent(sp.Skeleton);
  592. skeletonComp.skeletonData = skData;
  593. skeletonComp.setAnimation(0, 'animation', loop);
  594. // 设置父节点和位置
  595. const targetParent = parent || find('Canvas/GameLevelUI/enemyContainer') || find('Canvas');
  596. if (targetParent) {
  597. targetParent.addChild(effectNode);
  598. if (parent) {
  599. effectNode.setPosition(0, 0, 0);
  600. } else {
  601. const parentTrans = targetParent.getComponent(UITransform);
  602. if (parentTrans) {
  603. const localPos = parentTrans.convertToNodeSpaceAR(worldPos);
  604. effectNode.position = localPos;
  605. }
  606. }
  607. }
  608. // 非循环动画播放完毕后销毁节点
  609. if (!loop) {
  610. skeletonComp.setCompleteListener(() => {
  611. if (effectNode && effectNode.isValid) {
  612. effectNode.destroy();
  613. }
  614. });
  615. }
  616. // 调用回调函数,传递创建的特效节点
  617. if (onCreated) {
  618. onCreated(effectNode);
  619. }
  620. }).catch((err) => {
  621. console.warn('加载特效失败:', path, err);
  622. });
  623. }
  624. /**
  625. * 清理资源
  626. */
  627. onDestroy() {
  628. // 不再强制销毁燃烧区域,让它们按照自己的持续时间自然销毁
  629. // 燃烧区域现在由GroundBurnAreaManager统一管理,有自己的生命周期
  630. // 只清空引用,不销毁燃烧区域节点
  631. this.activeBurnAreas = [];
  632. // 清理检测碰撞器事件监听
  633. if (this.detectionCollider) {
  634. this.detectionCollider.off(Contact2DType.BEGIN_CONTACT, this.onDetectionEnter, this);
  635. this.detectionCollider.off(Contact2DType.END_CONTACT, this.onDetectionExit, this);
  636. this.detectionCollider = null;
  637. }
  638. // 清理检测到的敌人集合
  639. this.detectedEnemies.clear();
  640. // 重置锯齿草状态
  641. this.resetSawGrassState();
  642. }
  643. /**
  644. * 设置检测范围碰撞器事件监听(用于手动添加的CircleCollider2D)
  645. */
  646. private setupDetectionColliderEvents() {
  647. // 首先在当前节点查找CircleCollider2D组件
  648. let colliders = this.getComponents(CircleCollider2D);
  649. // 如果当前节点没有找到,则在子节点中递归查找
  650. if (colliders.length === 0) {
  651. colliders = this.getComponentsInChildren(CircleCollider2D);
  652. }
  653. // 找到用作检测范围的CircleCollider2D(通常是sensor模式的)
  654. for (const collider of colliders) {
  655. if (collider.sensor) { // 只要是sensor模式的CircleCollider2D就认为是检测范围碰撞器
  656. this.detectionCollider = collider;
  657. // 启用碰撞监听 - Cocos Creator 3.8.6正确的事件类型
  658. this.detectionCollider.on(Contact2DType.BEGIN_CONTACT, this.onDetectionEnter, this);
  659. this.detectionCollider.on(Contact2DType.END_CONTACT, this.onDetectionExit, this);
  660. break;
  661. }
  662. }
  663. if (!this.detectionCollider) {
  664. console.log(`[BulletHitEffect] 未找到检测范围碰撞器,将使用实时计算方式`);
  665. }
  666. }
  667. /**
  668. * 检测范围进入事件
  669. */
  670. private onDetectionEnter(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  671. const otherNode = otherCollider.node;
  672. if (this.isEnemyNode(otherNode)) {
  673. // 获取武器信息,确认是否为锯齿草武器
  674. const weaponBullet = this.getComponent(WeaponBullet);
  675. const weaponInfo = weaponBullet ? weaponBullet.getWeaponInfo() : null;
  676. const weaponId = weaponInfo ? weaponInfo.getWeaponId() : null;
  677. // 对于锯齿草武器,记录所有检测到的敌人,但在弹射时会根据hasFirstHit状态进行过滤
  678. this.detectedEnemies.add(otherNode);
  679. if (weaponId === 'saw_grass') {
  680. const hitStatus = this.hasFirstHit ? '已首次击中' : '尚未首次击中';
  681. }
  682. }
  683. }
  684. /**
  685. * 检测范围退出事件
  686. */
  687. private onDetectionExit(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  688. const otherNode = otherCollider.node;
  689. if (this.isEnemyNode(otherNode)) {
  690. this.detectedEnemies.delete(otherNode);
  691. // 获取武器信息,确认是否为锯齿草武器
  692. const weaponBullet = this.getComponent(WeaponBullet);
  693. const weaponInfo = weaponBullet ? weaponBullet.getWeaponInfo() : null;
  694. const weaponId = weaponInfo ? weaponInfo.getWeaponId() : null;
  695. if (weaponId === 'saw_grass') {
  696. console.log(`🌿 [锯齿草检测] 锯齿草武器敌人离开: ${otherNode.name}`);
  697. }
  698. }
  699. }
  700. /**
  701. * 获取命中统计
  702. */
  703. public getHitStats() {
  704. return {
  705. hitCount: this.hitCount,
  706. pierceCount: this.pierceCount,
  707. ricochetCount: this.ricochetCount
  708. };
  709. }
  710. /**
  711. * 验证配置
  712. */
  713. public static validateConfig(effects: HitEffectConfig[]): boolean {
  714. if (!Array.isArray(effects) || effects.length === 0) return false;
  715. for (const effect of effects) {
  716. if (!effect.type || effect.priority < 0) return false;
  717. if (!effect.params) return false;
  718. }
  719. return true;
  720. }
  721. private spawnHitEffect(worldPos: Vec3) {
  722. const path = this.defaultHitEffectPath;
  723. if (path) {
  724. this.spawnEffect(path, worldPos, false);
  725. }
  726. }
  727. /**
  728. * 重置锯齿草状态
  729. */
  730. private resetSawGrassState() {
  731. this.hasFirstHit = false;
  732. this.currentTargetEnemy = null;
  733. }
  734. }