WeaponBullet.ts 36 KB

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