WeaponBullet.ts 20 KB

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