WeaponBullet.ts 26 KB

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