WeaponBullet.ts 34 KB

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