WeaponBullet.ts 30 KB

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