WeaponBullet.ts 26 KB

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