WeaponBullet.ts 27 KB

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