WeaponBullet.ts 34 KB

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