WeaponBullet.ts 33 KB

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