WeaponBullet.ts 30 KB

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