WeaponBullet.ts 19 KB

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