BulletHitEffect.ts 34 KB

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