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