WeaponBullet.ts 24 KB

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