WeaponBullet.ts 19 KB

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