WeaponBullet.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. import { _decorator, Component, Node, Vec2, Vec3, RigidBody2D, Collider2D, Contact2DType, IPhysics2DContact, find, Prefab, instantiate, UITransform, resources, sp, JsonAsset, Sprite, SpriteFrame, math } from 'cc';
  2. import { JsonConfigLoader } from '../Core/JsonConfigLoader';
  3. import { BundleLoader } from '../Core/BundleLoader';
  4. import { BulletCount, BulletSpawnInfo } from './BulletEffects/BulletCount';
  5. import { BulletTrajectory } from './BulletEffects/BulletTrajectory';
  6. import { BulletHitEffect, HitResult } from './BulletEffects/BulletHitEffect';
  7. import { BulletLifecycle } from './BulletEffects/BulletLifecycle';
  8. import { BulletTrailController } from './BulletTrailController';
  9. import { EnemyAttackStateManager } from './EnemyAttackStateManager';
  10. import { ConfigManager, WeaponConfig, BulletCountConfig, BulletTrajectoryConfig, HitEffectConfig, BulletLifecycleConfig } from '../Core/ConfigManager';
  11. import EventBus,{ GameEvents } from '../Core/EventBus';
  12. import { PersistentSkillManager } from '../FourUI/SkillSystem/PersistentSkillManager';
  13. import { SkillManager } from './SkillSelection/SkillManager';
  14. import { SaveDataManager } from '../LevelSystem/SaveDataManager';
  15. import { WeaponInfo } from './BlockSelection/WeaponInfo';
  16. import { BlockInfo } from './BlockSelection/BlockInfo';
  17. const { ccclass, property } = _decorator;
  18. /**
  19. * WeaponBullet - 重构后的统一子弹控制器
  20. *
  21. * 整合四个子模块:
  22. * 1. BulletCount - 子弹数量控制
  23. * 2. BulletTrajectory - 弹道控制
  24. * 3. BulletHitEffect - 命中效果(可叠加)
  25. * 4. BulletLifecycle - 生命周期控制
  26. *
  27. * 从weapons.json读取配置并分发给各模块
  28. */
  29. export interface BulletInitData {
  30. weaponId: string; // 武器ID,用于查找配置
  31. firePosition: Vec3; // 发射位置
  32. direction?: Vec3; // 发射方向(可选)
  33. autoTarget?: boolean; // 是否自动瞄准
  34. weaponConfig?: WeaponConfig; // 直接传入的武器配置(优先级更高)
  35. weaponInfo?: WeaponInfo; // WeaponInfo组件实例(用于冷却管理等)
  36. blockInfo?: BlockInfo; // BlockInfo组件实例(用于获取稀有度等级)
  37. sourceBlock?: Node; // 发射源方块节点(用于回旋镖返回)
  38. }
  39. @ccclass('WeaponBullet')
  40. export class WeaponBullet extends Component {
  41. /* ========= 全局开关:是否允许生成子弹 ========= */
  42. private static shootingEnabled: boolean = true;
  43. public static setShootingEnabled(enable: boolean) {
  44. WeaponBullet.shootingEnabled = enable;
  45. }
  46. // 子弹组件
  47. private bulletTrajectory: BulletTrajectory = null;
  48. private bulletHitEffect: BulletHitEffect = null;
  49. private bulletLifecycle: BulletLifecycle = null;
  50. private bulletTrailController: BulletTrailController = null;
  51. // 武器配置和状态
  52. private weaponConfig: WeaponConfig = null;
  53. private weaponId: string = null; // 存储武器ID用于获取升级数据
  54. private weaponInfo: WeaponInfo = null; // WeaponInfo组件实例
  55. private blockInfo: BlockInfo = null; // BlockInfo组件实例
  56. private sourceBlock: Node = null; // 发射源方块节点(用于回旋镖返回)
  57. private isInitialized: boolean = false;
  58. // === 静态武器配置缓存 ===
  59. private static weaponsData: any = null;
  60. // === 自动旋转相关 ===
  61. private readonly _rotationSpeedDeg: number = 720; // 每秒旋转 720° (度)
  62. private readonly _rotationSpeedRad: number = 720 * Math.PI / 180; // 转换为弧度,用于物理角速度
  63. // === 方向偏移映射(使图片“前进方向”与运动方向一致)===
  64. // 默认这些图片的“上”为前进方向,所以与数学上的0度(向右)存在90度差异
  65. private readonly _orientationOffsetByWeapon: Record<string, number> = {
  66. 'sharp_carrot': -90,
  67. 'hot_pepper': -90,
  68. 'okra_missile': -90,
  69. 'mace_club': -90
  70. };
  71. private getOrientationOffset(): number {
  72. const id = this.weaponConfig?.id;
  73. if (!id) return 0;
  74. return this._orientationOffsetByWeapon[id] ?? 0;
  75. }
  76. private enableFacingSyncIfNeeded(): void {
  77. // shouldRotate === false 时,不做自旋;按即时速度方向对齐外观
  78. const shouldRotate = this.weaponConfig?.bulletConfig?.shouldRotate;
  79. if (shouldRotate === false) {
  80. const pelletNode = this.node.getChildByName('Pellet');
  81. const targetNode = pelletNode || this.node;
  82. const offset = this.getOrientationOffset();
  83. this.schedule((dt: number) => {
  84. if (!this.bulletTrajectory) return;
  85. const vel = this.bulletTrajectory.getCurrentVelocity();
  86. if (!vel || (Math.abs(vel.x) < 1e-4 && Math.abs(vel.y) < 1e-4)) return;
  87. const deg = math.toDegree(Math.atan2(vel.y, vel.x)) + offset;
  88. if (targetNode && targetNode.isValid) {
  89. targetNode.angle = deg;
  90. }
  91. }, 0);
  92. }
  93. }
  94. /**
  95. * 加载武器配置数据
  96. */
  97. public static async loadWeaponsData(): Promise<void> {
  98. if (WeaponBullet.weaponsData) {
  99. return;
  100. }
  101. try {
  102. const jsonConfigLoader = JsonConfigLoader.getInstance();
  103. const weaponData = await jsonConfigLoader.loadConfig('weapons');
  104. if (!weaponData) {
  105. throw new Error('武器配置文件内容为空');
  106. }
  107. WeaponBullet.weaponsData = weaponData;
  108. } catch (error) {
  109. console.error('[WeaponBullet] 武器配置文件加载失败:', error);
  110. throw error;
  111. }
  112. }
  113. /**
  114. * 根据武器ID获取配置
  115. */
  116. public static getWeaponConfig(weaponId: string): WeaponConfig | null {
  117. if (!WeaponBullet.weaponsData) {
  118. return null;
  119. }
  120. const weapons = WeaponBullet.weaponsData.weapons;
  121. const weapon = weapons.find((w: any) => w.id === weaponId);
  122. if (!weapon) {
  123. return null;
  124. }
  125. return weapon as WeaponConfig;
  126. }
  127. /**
  128. * 创建多发子弹
  129. */
  130. public static createBullets(initData: BulletInitData, bulletPrefab: Node): Node[] {
  131. // 关卡备战或其他情况下可关闭生成
  132. if (!WeaponBullet.shootingEnabled) return [];
  133. // 触发子弹创建请求事件
  134. const eventBus = EventBus.getInstance();
  135. eventBus.emit(GameEvents.BULLET_CREATE_REQUEST, { weaponId: initData.weaponId, position: initData.firePosition });
  136. // 通过事件系统检查是否可以发射子弹
  137. let canFire = true;
  138. eventBus.emit(GameEvents.BALL_FIRE_BULLET, { canFire: (result: boolean) => { canFire = result; } });
  139. if (!canFire) {
  140. return [];
  141. }
  142. // 获取武器配置
  143. const originalConfig = initData.weaponConfig || WeaponBullet.getWeaponConfig(initData.weaponId);
  144. if (!originalConfig) {
  145. return [];
  146. }
  147. // === 应用多重射击技能 ===
  148. const config = BulletCount.applyMultiShotSkill(originalConfig);
  149. // === 计算基础发射方向 ===
  150. let direction: Vec3;
  151. if (initData.direction) {
  152. direction = initData.direction.clone();
  153. } else if (initData.autoTarget) {
  154. // 通过事件系统获取最近敌人
  155. let nearestEnemy: Node = null;
  156. eventBus.emit(GameEvents.ENEMY_GET_NEAREST, {
  157. position: initData.firePosition,
  158. callback: (enemy: Node) => { nearestEnemy = enemy; }
  159. });
  160. if (nearestEnemy) {
  161. direction = nearestEnemy.worldPosition.clone().subtract(initData.firePosition).normalize();
  162. }
  163. // 自动瞄准未找到有效目标时,不发射子弹
  164. if (!direction) {
  165. console.log('[WeaponBullet] 自动瞄准未找到有效目标,取消发射子弹');
  166. return [];
  167. }
  168. } else {
  169. direction = new Vec3(1, 0, 0);
  170. }
  171. const spawnInfos = BulletCount.calculateBulletSpawns(
  172. config.bulletConfig.count,
  173. initData.firePosition,
  174. direction
  175. );
  176. const bullets: Node[] = [];
  177. // 为每个子弹创建实例
  178. for (const spawnInfo of spawnInfos) {
  179. const createBullet = () => {
  180. try {
  181. const bullet = instantiate(bulletPrefab);
  182. const weaponBullet = bullet.getComponent(WeaponBullet) || bullet.addComponent(WeaponBullet);
  183. // 初始化子弹
  184. weaponBullet.init({
  185. ...initData,
  186. firePosition: spawnInfo.position,
  187. direction: spawnInfo.direction,
  188. weaponConfig: config
  189. });
  190. return bullet;
  191. } catch (error) {
  192. console.error(`[WeaponBullet] 子弹创建失败:`, error);
  193. return null;
  194. }
  195. };
  196. // 处理延迟发射 - 对于burst模式,所有子弹都应该被创建并返回
  197. if (spawnInfo.delay > 0) {
  198. // 延迟发射:先创建子弹,然后延迟激活
  199. const bullet = createBullet();
  200. if (bullet) {
  201. // 先禁用子弹,延迟后再激活
  202. bullet.active = false;
  203. bullets.push(bullet);
  204. setTimeout(() => {
  205. if (bullet && bullet.isValid) {
  206. bullet.active = true;
  207. //console.log(`[WeaponBullet] 延迟子弹激活 - 延迟: ${spawnInfo.delay}ms`);
  208. }
  209. }, spawnInfo.delay);
  210. }
  211. } else {
  212. const bullet = createBullet();
  213. if (bullet) {
  214. bullets.push(bullet);
  215. }
  216. }
  217. }
  218. return bullets;
  219. }
  220. /**
  221. * 初始化子弹
  222. */
  223. public init(initData: BulletInitData) {
  224. // 通过事件系统检查游戏是否暂停,暂停时不初始化子弹
  225. let bulletFireEnabled = true;
  226. EventBus.getInstance().emit(GameEvents.BALL_FIRE_BULLET, { canFire: (result: boolean) => { bulletFireEnabled = result; } });
  227. if (!bulletFireEnabled) {
  228. // 立即销毁自己
  229. this.node.destroy();
  230. return;
  231. }
  232. // 验证初始化数据
  233. if (!WeaponBullet.validateInitData(initData)) {
  234. console.error('WeaponBullet.init: 初始化数据无效');
  235. this.node.destroy();
  236. return;
  237. }
  238. // 存储武器ID、WeaponInfo、BlockInfo和SourceBlock
  239. this.weaponId = initData.weaponId;
  240. this.weaponInfo = initData.weaponInfo || null;
  241. this.blockInfo = initData.blockInfo || null;
  242. this.sourceBlock = initData.sourceBlock || null;
  243. // 获取武器配置
  244. this.weaponConfig = initData.weaponConfig || WeaponBullet.getWeaponConfig(initData.weaponId);
  245. if (!this.weaponConfig) {
  246. console.error(`WeaponBullet.init: 无法找到武器配置 ${initData.weaponId}`);
  247. this.node.destroy();
  248. return;
  249. }
  250. // 应用技能加成计算运行时数值
  251. this.calculateRuntimeStats();
  252. // 使用世界坐标设置位置
  253. this.setPositionInGameArea(initData.firePosition);
  254. // 初始化各个组件
  255. this.initializeComponents(initData);
  256. // 设置子弹外观
  257. this.setupBulletSprite();
  258. // 设置子弹效果节点激活状态
  259. this.setupBulletEffectNodes();
  260. // 设置碰撞监听
  261. this.setupCollisionListener();
  262. // 启用 shouldRotate=false 时的速度朝向同步(对齐拖尾)
  263. this.enableFacingSyncIfNeeded();
  264. this.isInitialized = true;
  265. }
  266. /**
  267. * 在GameArea中设置位置
  268. */
  269. private setPositionInGameArea(worldPos: Vec3) {
  270. const gameArea = find('Canvas/GameLevelUI/GameArea');
  271. if (gameArea) {
  272. const gameAreaTransform = gameArea.getComponent(UITransform);
  273. if (gameAreaTransform) {
  274. const localPos = gameAreaTransform.convertToNodeSpaceAR(worldPos);
  275. this.node.position = localPos;
  276. }
  277. }
  278. }
  279. /**
  280. * 初始化各个组件
  281. */
  282. private initializeComponents(initData: BulletInitData) {
  283. const config = this.weaponConfig.bulletConfig;
  284. // 确保物理组件存在
  285. this.setupPhysics();
  286. // 初始化弹道组件
  287. this.bulletTrajectory = this.getComponent(BulletTrajectory) || this.addComponent(BulletTrajectory);
  288. const trajCfg: BulletTrajectoryConfig = { ...config.trajectory, speed: this.weaponConfig.stats.bulletSpeed };
  289. // 计算方向
  290. const direction = initData.direction || this.calculateDirection(initData.autoTarget);
  291. // 自动瞄准且未找到目标时,取消初始化子弹
  292. if (!direction && initData.autoTarget) {
  293. console.log('[WeaponBullet] 自动瞄准未找到目标,取消初始化子弹');
  294. this.node.destroy();
  295. return;
  296. }
  297. // === 根据发射方向调整朝向 ===
  298. // 说明:
  299. // - 当 shouldRotate !== false 时,保持父节点按发射方向旋转,并启用持续自旋转(原逻辑)。
  300. // - 当 shouldRotate === false 时,仅旋转 Pellet 子节点,避免父子叠加导致角度加倍。
  301. // - 对尖胡萝卜(sharp_carrot)应用图片朝向校正:以图片上方为正方向,发射时上方朝向发射方向,尖头沿轨迹。
  302. if (direction) {
  303. const deg = math.toDegree(Math.atan2(direction.y, direction.x));
  304. if (config.shouldRotate !== false) {
  305. // 父节点按发射方向对齐
  306. this.node.angle = deg;
  307. // 启用持续自旋转
  308. this.applyAutoRotation();
  309. } else {
  310. const pelletNode = this.node.getChildByName('Pellet');
  311. // 针对尖胡萝卜图片的朝向校正:图片默认“上”为正,需减去90度使“上”对齐发射方向
  312. const carrotOffset = (this.weaponConfig?.id === 'sharp_carrot') ? -90 : 0;
  313. const finalDeg = deg + carrotOffset;
  314. if (pelletNode) {
  315. pelletNode.angle = finalDeg;
  316. } else {
  317. // 若无Pellet子节点,退化为旋转父节点
  318. this.node.angle = finalDeg;
  319. }
  320. }
  321. }
  322. this.bulletTrajectory.init(
  323. trajCfg,
  324. direction,
  325. initData.firePosition,
  326. this.sourceBlock // 传递发射源方块节点
  327. );
  328. // --- 额外偏移 ---
  329. const dir = direction.clone().normalize();
  330. const spawnOffset = 30;
  331. if (!Number.isNaN(dir.x) && !Number.isNaN(dir.y)) {
  332. const newLocalPos = this.node.position.clone().add(new Vec3(dir.x * spawnOffset, dir.y * spawnOffset, 0));
  333. this.node.setPosition(newLocalPos);
  334. }
  335. // 初始化命中效果组件
  336. this.bulletHitEffect = this.getComponent(BulletHitEffect) || this.addComponent(BulletHitEffect);
  337. this.bulletHitEffect.init(config.hitEffects);
  338. // 传递默认特效路径
  339. if (this.bulletHitEffect && config.visual) {
  340. (this.bulletHitEffect as any).setDefaultEffects?.(config.visual.hitEffect, config.visual.trailEffect, (config.visual as any).burnEffect);
  341. }
  342. // 初始化生命周期组件
  343. this.bulletLifecycle = this.getComponent(BulletLifecycle) || this.addComponent(BulletLifecycle);
  344. // 为回旋镖类型的武器设置maxRange,如果配置中没有设置的话
  345. const lifecycleConfig = { ...config.lifecycle };
  346. if (lifecycleConfig.type === 'return_trip' && !lifecycleConfig.maxRange && this.weaponConfig.stats.range) {
  347. lifecycleConfig.maxRange = this.weaponConfig.stats.range;
  348. }
  349. this.bulletLifecycle.init(lifecycleConfig, initData.firePosition);
  350. // 设置碰撞监听
  351. this.setupCollisionListener();
  352. this.isInitialized = true;
  353. }
  354. /**
  355. * 设置物理组件
  356. */
  357. private setupPhysics() {
  358. const rigidBody = this.getComponent(RigidBody2D);
  359. if (rigidBody) {
  360. rigidBody.enabledContactListener = true;
  361. rigidBody.gravityScale = 0; // 由弹道组件控制重力
  362. rigidBody.linearDamping = 0;
  363. rigidBody.angularDamping = 0;
  364. rigidBody.allowSleep = false;
  365. // 如果节点包含子节点 'Pellet',表示这是带容器的子弹;锁定容器旋转
  366. if (this.node.getChildByName('Pellet')) {
  367. rigidBody.fixedRotation = true;
  368. }
  369. }
  370. const collider = this.getComponent(Collider2D);
  371. if (collider) {
  372. collider.sensor = false;
  373. collider.on(Contact2DType.BEGIN_CONTACT, this.onHit, this);
  374. }
  375. }
  376. /**
  377. * 计算子弹方向
  378. */
  379. private calculateDirection(autoTarget: boolean = false): Vec3 | null {
  380. if (!autoTarget) {
  381. // 随机方向
  382. const angle = Math.random() * Math.PI * 2;
  383. return new Vec3(Math.cos(angle), Math.sin(angle), 0);
  384. }
  385. // 寻找最近敌人(使用静态工具函数)
  386. const nearestEnemy = WeaponBullet.findNearestEnemyGlobal(this.node.worldPosition);
  387. if (nearestEnemy) {
  388. const direction = nearestEnemy.worldPosition.clone()
  389. .subtract(this.node.worldPosition)
  390. .normalize();
  391. return direction;
  392. }
  393. // 自动瞄准模式下,无目标则返回 null,不再随机发射
  394. return null;
  395. }
  396. /**
  397. * 设置碰撞监听
  398. */
  399. private setupCollisionListener() {
  400. // 碰撞监听已在setupPhysics中设置
  401. }
  402. /**
  403. * 碰撞处理
  404. */
  405. private onHit(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  406. if (!this.isInitialized) return;
  407. const otherNode = otherCollider.node;
  408. // Ignore collisions with other bullets (prevent friendly-fire between shotgun pellets)
  409. if (otherNode.getComponent(WeaponBullet)) {
  410. return; // Skip further processing if the collider is another bullet
  411. }
  412. // 检查是否命中敌人并触发事件
  413. let enemyRootNode: Node = null;
  414. // 检查是否碰撞到EnemySprite子节点
  415. if (otherNode.name === 'EnemySprite' && otherNode.parent) {
  416. // 如果碰撞到EnemySprite,获取其父节点(敌人根节点)
  417. const parentNode = otherNode.parent;
  418. if (parentNode.getComponent('EnemyInstance')) {
  419. enemyRootNode = parentNode;
  420. }
  421. }
  422. // 兼容旧的敌人检测逻辑(直接碰撞到敌人根节点)
  423. else if (otherNode.name.toLowerCase().includes('enemy') ||
  424. otherNode.name.toLowerCase().includes('敌人') ||
  425. otherNode.getComponent('EnemyInstance')) {
  426. enemyRootNode = otherNode;
  427. }
  428. if (enemyRootNode) {
  429. // 检查敌人是否处于漂移状态,如果是则不触发攻击
  430. const enemyInstance = enemyRootNode.getComponent('EnemyInstance') as any;
  431. if (enemyInstance && enemyInstance.isDrifting()) {
  432. console.log(`[WeaponBullet] 敌人 ${enemyRootNode.name} 正在漂移中,跳过子弹攻击`);
  433. return; // 漂移状态下不受到子弹攻击
  434. }
  435. // 使用EnemyAttackStateManager检查敌人是否可攻击(包括隐身状态)
  436. const attackStateManager = EnemyAttackStateManager.getInstance();
  437. if (!attackStateManager.isEnemyAttackable(enemyRootNode)) {
  438. console.log(`[WeaponBullet] 敌人 ${enemyRootNode.name} 不可攻击(可能处于隐身状态),跳过子弹攻击`);
  439. return; // 不可攻击状态下不受到子弹攻击
  440. }
  441. // 计算是否暴击
  442. const isCritical = Math.random() < this.getCritChance();
  443. const finalDamage = isCritical ? this.getFinalCritDamage() : this.getFinalDamage();
  444. // 若为爆炸类型子弹,则不在碰撞处直接结算一次伤害,避免与范围爆炸重复
  445. if (!this.bulletHitEffect || !this.bulletHitEffect.hasExplosionEffect()) {
  446. // 触发子弹命中敌人事件(非爆炸型)
  447. EventBus.getInstance().emit(GameEvents.BULLET_HIT_ENEMY, {
  448. enemyNode: enemyRootNode,
  449. damage: finalDamage,
  450. isCritical: isCritical,
  451. source: `WeaponBullet-${this.weaponConfig?.id || 'unknown'}`
  452. });
  453. }
  454. }
  455. // 获取碰撞世界坐标
  456. let contactWorldPos: Vec3 = null;
  457. if (contact && (contact as any).getWorldManifold) {
  458. const wm = (contact as any).getWorldManifold();
  459. if (wm && wm.points && wm.points.length > 0) {
  460. contactWorldPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  461. }
  462. }
  463. if (!contactWorldPos) {
  464. contactWorldPos = otherNode.worldPosition.clone();
  465. }
  466. // 处理命中效果
  467. const hitResult: HitResult = this.bulletHitEffect.processHit(otherNode, contactWorldPos);
  468. // 通知生命周期组件发生命中(可能影响内部计数或阶段)
  469. if (this.bulletLifecycle) {
  470. this.bulletLifecycle.onHit(otherNode);
  471. }
  472. // 不直接销毁,交由 BulletLifecycle 自行处理
  473. // 生命周期和命中效果自行决定是否销毁;此处不再直接销毁,由 BulletLifecycle.update() 完成
  474. if (hitResult.shouldRicochet) {
  475. // 执行弹射逻辑:BulletHitEffect已经在processHit中处理了弹射方向改变
  476. // 这里不需要额外操作,弹射方向已经通过calculateRicochetDirection更新
  477. } else if (hitResult.shouldContinue) {
  478. // 这里需要实现子弹继续飞行的逻辑
  479. }
  480. }
  481. /**
  482. * 为子弹设置持续旋转(通过刚体角速度,避免被物理系统覆盖)
  483. */
  484. private applyAutoRotation() {
  485. // 若存在子节点 Pellet,则只旋转 Pellet,容器保持角度不变
  486. const pelletNode = this.node.getChildByName('Pellet');
  487. if (pelletNode) {
  488. this.schedule((dt: number) => {
  489. pelletNode.angle += this._rotationSpeedDeg * dt;
  490. }, 0);
  491. return;
  492. }
  493. const rigidBody = this.getComponent(RigidBody2D);
  494. if (rigidBody) {
  495. rigidBody.angularVelocity = this._rotationSpeedRad; // 弧度/秒
  496. rigidBody.angularDamping = 0; // 无角阻尼,保持恒定旋转
  497. } else {
  498. // 如果没有刚体,退化为在 update 中手动旋转
  499. this.schedule((dt: number) => {
  500. this.node.angle += this._rotationSpeedDeg * dt;
  501. }, 0);
  502. }
  503. }
  504. /**
  505. * 获取武器配置
  506. */
  507. public getWeaponConfig(): WeaponConfig {
  508. return this.weaponConfig;
  509. }
  510. /**
  511. * 获取WeaponInfo组件实例
  512. */
  513. public getWeaponInfo(): WeaponInfo | null {
  514. return this.weaponInfo;
  515. }
  516. /**
  517. * 获取子弹状态信息
  518. */
  519. public getBulletStatus() {
  520. return {
  521. isInitialized: this.isInitialized,
  522. weaponName: this.weaponConfig?.name,
  523. trajectoryState: this.bulletTrajectory?.getState(),
  524. lifecycleState: this.bulletLifecycle?.getState(),
  525. hitStats: this.bulletHitEffect?.getHitStats()
  526. };
  527. }
  528. /**
  529. * 强制销毁子弹
  530. */
  531. public forceDestroy() {
  532. if (this.bulletLifecycle) {
  533. this.bulletLifecycle.forceDestroy();
  534. }
  535. }
  536. /**
  537. * 清理所有活跃的子弹 - 游戏重置时使用
  538. */
  539. public static clearAllBullets() {
  540. console.log('[WeaponBullet] 开始清理所有活跃子弹');
  541. // 查找GameArea节点,子弹都添加在这里
  542. const gameArea = find('Canvas/GameLevelUI/GameArea');
  543. if (!gameArea) {
  544. console.log('[WeaponBullet] 未找到GameArea节点');
  545. return;
  546. }
  547. let bulletCount = 0;
  548. const bulletsToDestroy: Node[] = [];
  549. // 遍历GameArea的所有子节点,查找WeaponBullet组件
  550. for (const child of gameArea.children) {
  551. if (child && child.isValid) {
  552. const weaponBullet = child.getComponent(WeaponBullet);
  553. if (weaponBullet) {
  554. bulletsToDestroy.push(child);
  555. bulletCount++;
  556. }
  557. }
  558. }
  559. // 销毁所有找到的子弹
  560. for (const bullet of bulletsToDestroy) {
  561. if (bullet && bullet.isValid) {
  562. bullet.destroy();
  563. }
  564. }
  565. console.log(`[WeaponBullet] 清理完成,共销毁 ${bulletCount} 个子弹`);
  566. }
  567. /**
  568. * 验证初始化数据
  569. */
  570. public static validateInitData(initData: BulletInitData): boolean {
  571. if (!initData) return false;
  572. if (!initData.weaponId && !initData.weaponConfig) return false;
  573. if (!initData.firePosition) return false;
  574. return true;
  575. }
  576. onDestroy() {
  577. // 清理事件监听
  578. const collider = this.getComponent(Collider2D);
  579. if (collider) {
  580. collider.off(Contact2DType.BEGIN_CONTACT, this.onHit, this);
  581. }
  582. // 取消所有调度器,避免旋转/朝向同步在销毁后继续运行
  583. this.unscheduleAllCallbacks();
  584. // 清理拖尾控制器
  585. if (this.bulletTrailController) {
  586. this.bulletTrailController.resetTrail();
  587. this.bulletTrailController = null;
  588. }
  589. }
  590. /**
  591. * 设置子弹的SpriteFrame,使其与方块武器 (WeaponBlock/B1/Weapon) 节点上的SpriteFrame 一致
  592. */
  593. private setupBulletSprite() {
  594. // 先尝试获取当前节点上的 Sprite 组件,若不存在则在子节点中查找
  595. const sprite: Sprite | null = this.getComponent(Sprite) || this.node.getComponentInChildren(Sprite);
  596. if (!sprite) {
  597. console.log("未找到Sprite组件");
  598. // 子弹预制体可能没有Sprite组件,直接返回
  599. return;
  600. }
  601. // 使用武器配置中的bulletConfig.visual.bulletImages字段获取子弹图像路径
  602. const bulletImagePath = this.weaponConfig?.bulletConfig?.visual?.bulletImages;
  603. if (!bulletImagePath) {
  604. console.log("未找到子弹图像配置 (bulletConfig.visual.bulletImages)");
  605. return;
  606. }
  607. // 转换路径格式,去除"images/"前缀
  608. const bundlePath = bulletImagePath.replace(/^images\//, '');
  609. const framePath = `${bundlePath}/spriteFrame`;
  610. // 使用BundleLoader从images Bundle加载SpriteFrame
  611. const bundleLoader = BundleLoader.getInstance();
  612. bundleLoader.loadSpriteFrame(framePath).then((spriteFrame) => {
  613. console.log("设置子弹外观");
  614. // Add comprehensive null safety checks before setting spriteFrame
  615. if (sprite && sprite.isValid &&
  616. this.node && this.node.isValid &&
  617. spriteFrame && spriteFrame.isValid) {
  618. sprite.spriteFrame = spriteFrame;
  619. console.log("设置子弹SpriteFrame成功");
  620. // === 子弹大小控制:保持prefab预设的大小 ===
  621. sprite.node.setScale(sprite.node.scale.x * 0.45, sprite.node.scale.y * 0.45, sprite.node.scale.z);
  622. }
  623. }).catch((err) => {
  624. console.error(`加载子弹SpriteFrame失败: ${err}`);
  625. });
  626. }
  627. /**
  628. * 设置子弹效果节点激活状态
  629. */
  630. private setupBulletEffectNodes() {
  631. // 查找Spine节点 - 现在所有武器都不使用Spine动画
  632. const spineNode = this.node.getChildByName('Spine');
  633. if (spineNode) {
  634. spineNode.active = false;
  635. }
  636. // 查找TrailEffect节点 - 武器都使用拖尾效果
  637. const trailEffectNode = this.node.getChildByName('TrailEffect');
  638. if (trailEffectNode) {
  639. trailEffectNode.active = true;
  640. // BulletTrailController 挂在容器节点上(PelletContainer),不是 TrailEffect 子节点
  641. const trailController = this.getComponent(BulletTrailController)
  642. || this.node.getComponentInChildren(BulletTrailController)
  643. || trailEffectNode.getComponent(BulletTrailController);
  644. if (trailController) {
  645. const id = this.weaponConfig?.id;
  646. if (id === 'okra_missile') {
  647. // 秋葵导弹专属拖尾:双层喷焰(边缘橙红,中心白色)
  648. if ((trailController as any).applyPresetRocketDualLayer) {
  649. (trailController as any).applyPresetRocketDualLayer();
  650. } else {
  651. // 回退到单层火焰色
  652. trailController.applyPresetRocket();
  653. }
  654. } else {
  655. // 默认:白色拖尾
  656. trailController.setTrailColor('white');
  657. }
  658. } else {
  659. console.warn('[WeaponBullet] 未找到 BulletTrailController,拖尾颜色无法按武器设置');
  660. }
  661. }
  662. }
  663. /**
  664. * 静态:根据给定世界坐标,寻找最近的敌人节点
  665. * 使用EnemyAttackStateManager进行高效查找
  666. */
  667. private static findNearestEnemyGlobal(worldPos: Vec3): Node | null {
  668. // 使用攻击状态管理器获取所有可攻击的敌人
  669. const attackStateManager = EnemyAttackStateManager.getInstance();
  670. const attackableEnemies = attackStateManager.getAttackableEnemies();
  671. if (attackableEnemies.length === 0) {
  672. return null;
  673. }
  674. let nearest: Node = null;
  675. let nearestDist = Infinity;
  676. for (const enemy of attackableEnemies) {
  677. if (!enemy || !enemy.isValid || !enemy.activeInHierarchy) {
  678. continue;
  679. }
  680. const dist = Vec3.distance(worldPos, enemy.worldPosition);
  681. if (dist < nearestDist) {
  682. nearestDist = dist;
  683. nearest = enemy;
  684. }
  685. }
  686. if (nearest) {
  687. console.log(`[WeaponBullet] 找到最近的可攻击敌人: ${nearest.name}, 距离: ${nearestDist.toFixed(2)}`);
  688. } else {
  689. console.log(`[WeaponBullet] 未找到可攻击的敌人`);
  690. }
  691. return nearest;
  692. }
  693. /**
  694. * 计算运行时数值(应用武器升级和技能加成)
  695. */
  696. private calculateRuntimeStats() {
  697. // 获取基础伤害
  698. let baseDamage = this.weaponConfig.stats.damage;
  699. // 应用武器升级加成 - 使用UpgradeController的伤害计算逻辑
  700. const saveDataManager = SaveDataManager.getInstance();
  701. if (saveDataManager && this.weaponId) {
  702. const weaponData = saveDataManager.getWeapon(this.weaponId);
  703. if (weaponData && weaponData.level > 0) {
  704. // 优先从武器配置的upgradeConfig中获取伤害值
  705. if (this.weaponConfig.upgradeConfig && this.weaponConfig.upgradeConfig.levels) {
  706. const levelConfig = this.weaponConfig.upgradeConfig.levels[weaponData.level.toString()];
  707. if (levelConfig && typeof levelConfig.damage === 'number') {
  708. baseDamage = levelConfig.damage;
  709. console.log(`[WeaponBullet] 从upgradeConfig获取伤害 - 武器ID: ${this.weaponId}, 等级: ${weaponData.level}, 伤害: ${baseDamage}`);
  710. } else {
  711. // 如果upgradeConfig中没有伤害值,使用基础伤害 + 等级加成作为后备
  712. baseDamage = this.weaponConfig.stats.damage + (weaponData.level - 1);
  713. console.log(`[WeaponBullet] 使用基础伤害计算 - 武器ID: ${this.weaponId}, 等级: ${weaponData.level}, 基础伤害: ${this.weaponConfig.stats.damage}, 升级后伤害: ${baseDamage}`);
  714. }
  715. } else {
  716. // 如果没有upgradeConfig,使用默认公式
  717. baseDamage = this.weaponConfig.stats.damage + (weaponData.level - 1);
  718. console.log(`[WeaponBullet] 无upgradeConfig,使用默认公式 - 武器ID: ${this.weaponId}, 等级: ${weaponData.level}, 升级后伤害: ${baseDamage}`);
  719. }
  720. }
  721. }
  722. // 应用稀有度伤害倍数(合成升级效果)
  723. // 优先从BlockInfo中获取稀有度等级,如果不存在则从武器配置中获取
  724. let rarityLevel = 0; // 默认为common(0)
  725. let rarityName = 'common';
  726. if (this.blockInfo) {
  727. rarityLevel = this.blockInfo.rarity;
  728. rarityName = this.blockInfo.getRarityName();
  729. } else if (this.weaponConfig && this.weaponConfig.rarity) {
  730. // 兼容旧的JSON配置方式
  731. rarityName = this.weaponConfig.rarity;
  732. }
  733. const rarityMultiplier = this.getRarityDamageMultiplierByLevel(rarityLevel);
  734. if (rarityMultiplier > 1) {
  735. baseDamage = baseDamage * rarityMultiplier;
  736. console.log(`[WeaponBullet] 稀有度伤害倍数应用 - 稀有度等级: ${rarityLevel}(${rarityName}), 倍数: ${rarityMultiplier}, 最终基础伤害: ${baseDamage}`);
  737. }
  738. const skillManager = PersistentSkillManager.getInstance();
  739. if (!skillManager) {
  740. // 如果没有技能管理器,使用升级后的基础数值
  741. this.weaponConfig.runtimeStats = {
  742. finalDamage: baseDamage,
  743. finalCritDamage: baseDamage,
  744. critChance: 0 // 基础暴击率0%
  745. };
  746. console.log(`[WeaponBullet] 无技能管理器 - 最终伤害: ${baseDamage}`);
  747. return;
  748. }
  749. // 应用技能伤害加成(基于升级后的伤害)
  750. const finalDamage = skillManager.applyDamageBonus(baseDamage);
  751. // 暴击伤害应该基于最终伤害计算,而不是基础伤害
  752. // 首先计算暴击倍数(默认2倍),然后应用技能暴击伤害加成
  753. const baseCritDamage = finalDamage * 2; // 基础暴击倍数2倍
  754. const finalCritDamage = skillManager.applyCritDamageBonus(baseCritDamage);
  755. // 应用局内技能暴击率加成
  756. const baseCritChance = 0; // 基础暴击率0%
  757. let critChance = baseCritChance;
  758. // 应用局内技能加成(SkillManager)
  759. const inGameSkillManager = SkillManager.getInstance();
  760. if (inGameSkillManager) {
  761. const critSkillLevel = inGameSkillManager.getSkillLevel('crit_chance');
  762. if (critSkillLevel > 0) {
  763. critChance = SkillManager.calculateCritChance(critChance, critSkillLevel);
  764. }
  765. }
  766. this.weaponConfig.runtimeStats = {
  767. finalDamage,
  768. finalCritDamage,
  769. critChance
  770. };
  771. // 输出详细的暴击率计算信息
  772. const inGameCritLevel = inGameSkillManager ? inGameSkillManager.getSkillLevel('crit_chance') : 0;
  773. const inGameCritBonus = inGameSkillManager && inGameCritLevel > 0 ?
  774. ((SkillManager.calculateCritChance(baseCritChance, inGameCritLevel) - baseCritChance) * 100).toFixed(1) : '0.0';
  775. console.log(`[WeaponBullet] 完整伤害计算完成 - 武器ID: ${this.weaponId}, 原始伤害: ${this.weaponConfig.stats.damage}, 稀有度: ${rarityName}, 计算后基础伤害: ${baseDamage}, 最终伤害: ${finalDamage}, 暴击伤害: ${finalCritDamage}`);
  776. console.log(`[WeaponBullet] 暴击率详情 - 基础: ${(baseCritChance * 100).toFixed(1)}%, 局内技能等级: ${inGameCritLevel}, 局内技能加成: +${inGameCritBonus}%, 最终暴击率: ${(critChance * 100).toFixed(1)}%`);
  777. }
  778. /**
  779. * 获取最终伤害值(应用技能加成后)
  780. */
  781. public getFinalDamage(): number {
  782. return this.weaponConfig?.runtimeStats?.finalDamage || this.weaponConfig?.stats?.damage || 0;
  783. }
  784. /**
  785. * 获取最终暴击伤害值(应用技能加成后)
  786. */
  787. public getFinalCritDamage(): number {
  788. return this.weaponConfig?.runtimeStats?.finalCritDamage || this.weaponConfig?.stats?.damage || 0;
  789. }
  790. /**
  791. * 获取暴击率
  792. */
  793. public getCritChance(): number {
  794. return this.weaponConfig?.runtimeStats?.critChance || 0;
  795. }
  796. /**
  797. * 根据稀有度等级获取伤害倍数
  798. * @param rarityLevel 稀有度等级 (0: common, 1: uncommon, 2: rare, 3: epic)
  799. * @returns 伤害倍数
  800. */
  801. private getRarityDamageMultiplierByLevel(rarityLevel: number): number {
  802. // 优先使用当前武器的稀有度伤害倍率配置
  803. if (this.weaponConfig && this.weaponConfig.rarityDamageMultipliers && Array.isArray(this.weaponConfig.rarityDamageMultipliers)) {
  804. const multipliers = this.weaponConfig.rarityDamageMultipliers;
  805. if (rarityLevel >= 0 && rarityLevel < multipliers.length) {
  806. return multipliers[rarityLevel];
  807. }
  808. }
  809. // 如果当前武器配置不存在,使用默认值
  810. switch (rarityLevel) {
  811. case 0: // common
  812. return 1; // 1级,无倍数
  813. case 1: // uncommon
  814. return 1.5; // 2级,1.5倍伤害
  815. case 2: // rare
  816. return 2.25; // 3级,2.25倍伤害
  817. case 3: // epic
  818. return 8; // 4级,8倍伤害
  819. default:
  820. return 1;
  821. }
  822. }
  823. }