WeaponBullet.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. this.bulletTrajectory.init(
  210. trajCfg,
  211. direction,
  212. initData.firePosition
  213. );
  214. // 设置子弹的外观(SpriteFrame 与武器方块一致)
  215. this.setupBulletSprite();
  216. // --- 额外偏移 ---
  217. // 若子弹在生成时与发射方块碰撞(位置重叠), 会立刻触发碰撞事件导致被销毁。
  218. // 因此在初始化完弹道后, 将子弹沿发射方向平移一小段距离(默认 30 像素左右)。
  219. const dir = direction.clone().normalize();
  220. const spawnOffset = 30; // 可根据子弹半径或方块大小调整
  221. if (!Number.isNaN(dir.x) && !Number.isNaN(dir.y)) {
  222. const newLocalPos = this.node.position.clone().add(new Vec3(dir.x * spawnOffset, dir.y * spawnOffset, 0));
  223. this.node.setPosition(newLocalPos);
  224. }
  225. // 初始化命中效果组件
  226. this.bulletHitEffect = this.getComponent(BulletHitEffect) || this.addComponent(BulletHitEffect);
  227. this.bulletHitEffect.init(config.hitEffects);
  228. // 传递默认特效路径
  229. if (this.bulletHitEffect && config.visual) {
  230. (this.bulletHitEffect as any).setDefaultEffects?.(config.visual.hitEffect, config.visual.trailEffect, (config.visual as any).burnEffect);
  231. }
  232. // 初始化生命周期组件
  233. this.bulletLifecycle = this.getComponent(BulletLifecycle) || this.addComponent(BulletLifecycle);
  234. this.bulletLifecycle.init(config.lifecycle, initData.firePosition);
  235. // 设置碰撞监听
  236. this.setupCollisionListener();
  237. this.isInitialized = true;
  238. }
  239. /**
  240. * 设置物理组件
  241. */
  242. private setupPhysics() {
  243. const rigidBody = this.getComponent(RigidBody2D);
  244. if (rigidBody) {
  245. rigidBody.enabledContactListener = true;
  246. rigidBody.gravityScale = 0; // 由弹道组件控制重力
  247. rigidBody.linearDamping = 0;
  248. rigidBody.angularDamping = 0;
  249. rigidBody.allowSleep = false;
  250. }
  251. const collider = this.getComponent(Collider2D);
  252. if (collider) {
  253. collider.sensor = false;
  254. collider.on(Contact2DType.BEGIN_CONTACT, this.onHit, this);
  255. }
  256. }
  257. /**
  258. * 计算子弹方向
  259. */
  260. private calculateDirection(autoTarget: boolean = false): Vec3 {
  261. if (!autoTarget) {
  262. // 随机方向
  263. const angle = Math.random() * Math.PI * 2;
  264. return new Vec3(Math.cos(angle), Math.sin(angle), 0);
  265. }
  266. // 寻找最近敌人(使用静态工具函数)
  267. const nearestEnemy = WeaponBullet.findNearestEnemyGlobal(this.node.worldPosition);
  268. if (nearestEnemy) {
  269. const direction = nearestEnemy.worldPosition.clone()
  270. .subtract(this.node.worldPosition)
  271. .normalize();
  272. return direction;
  273. }
  274. // 若没有敌人则随机方向发射
  275. const angle = Math.random() * Math.PI * 2;
  276. return new Vec3(Math.cos(angle), Math.sin(angle), 0);
  277. }
  278. /**
  279. * 设置碰撞监听
  280. */
  281. private setupCollisionListener() {
  282. // 碰撞监听已在setupPhysics中设置
  283. }
  284. /**
  285. * 碰撞处理
  286. */
  287. private onHit(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  288. if (!this.isInitialized) return;
  289. const otherNode = otherCollider.node;
  290. // Ignore collisions with other bullets (prevent friendly-fire between shotgun pellets)
  291. if (otherNode.getComponent(WeaponBullet)) {
  292. return; // Skip further processing if the collider is another bullet
  293. }
  294. // 获取碰撞世界坐标
  295. let contactWorldPos: Vec3 = null;
  296. if (contact && (contact as any).getWorldManifold) {
  297. const wm = (contact as any).getWorldManifold();
  298. if (wm && wm.points && wm.points.length > 0) {
  299. contactWorldPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  300. }
  301. }
  302. if (!contactWorldPos) {
  303. contactWorldPos = otherNode.worldPosition.clone();
  304. }
  305. // 处理命中效果
  306. const hitResult: HitResult = this.bulletHitEffect.processHit(otherNode, contactWorldPos);
  307. // 通知生命周期组件发生命中(可能影响内部计数或阶段)
  308. if (this.bulletLifecycle) {
  309. this.bulletLifecycle.onHit(otherNode);
  310. }
  311. // 不直接销毁,交由 BulletLifecycle 自行处理
  312. // 生命周期和命中效果自行决定是否销毁;此处不再直接销毁,由 BulletLifecycle.update() 完成
  313. if (hitResult.shouldRicochet) {
  314. // 这里需要实现子弹弹射的逻辑
  315. } else if (hitResult.shouldContinue) {
  316. // 这里需要实现子弹继续飞行的逻辑
  317. }
  318. }
  319. /**
  320. * 为子弹设置持续旋转(通过刚体角速度,避免被物理系统覆盖)
  321. */
  322. private applyAutoRotation() {
  323. const rigidBody = this.getComponent(RigidBody2D);
  324. if (rigidBody) {
  325. rigidBody.angularVelocity = this._rotationSpeedRad; // 弧度/秒
  326. rigidBody.angularDamping = 0; // 无角阻尼,保持恒定旋转
  327. } else {
  328. // 如果没有刚体,退化为在 update 中手动旋转
  329. this.schedule((dt: number) => {
  330. this.node.angle += this._rotationSpeedDeg * dt;
  331. }, 0);
  332. }
  333. }
  334. /**
  335. * 获取武器配置
  336. */
  337. public getWeaponConfig(): WeaponConfig {
  338. return this.weaponConfig;
  339. }
  340. /**
  341. * 获取子弹状态信息
  342. */
  343. public getBulletStatus() {
  344. return {
  345. isInitialized: this.isInitialized,
  346. weaponName: this.weaponConfig?.name,
  347. trajectoryState: this.bulletTrajectory?.getState(),
  348. lifecycleState: this.bulletLifecycle?.getState(),
  349. hitStats: this.bulletHitEffect?.getHitStats()
  350. };
  351. }
  352. /**
  353. * 强制销毁子弹
  354. */
  355. public forceDestroy() {
  356. if (this.bulletLifecycle) {
  357. this.bulletLifecycle.forceDestroy();
  358. }
  359. }
  360. /**
  361. * 验证初始化数据
  362. */
  363. public static validateInitData(initData: BulletInitData): boolean {
  364. if (!initData) return false;
  365. if (!initData.weaponId && !initData.weaponConfig) return false;
  366. if (!initData.firePosition) return false;
  367. return true;
  368. }
  369. onDestroy() {
  370. // 清理事件监听
  371. const collider = this.getComponent(Collider2D);
  372. if (collider) {
  373. collider.off(Contact2DType.BEGIN_CONTACT, this.onHit, this);
  374. }
  375. }
  376. /**
  377. * 设置子弹的SpriteFrame,使其与方块武器 (WeaponBlock/B1/Weapon) 节点上的SpriteFrame 一致
  378. */
  379. private setupBulletSprite() {
  380. // 先尝试获取当前节点上的 Sprite 组件,若不存在则在子节点中查找
  381. const sprite: Sprite | null = this.getComponent(Sprite) || this.node.getComponentInChildren(Sprite);
  382. if (!sprite) {
  383. // 子弹预制体可能没有Sprite组件,直接返回
  384. return;
  385. }
  386. // weaponConfig.visualConfig.weaponSprites 中存储了各尺寸的SpriteFrame路径
  387. const spriteConfig = (this.weaponConfig as any)?.visualConfig?.weaponSprites;
  388. if (!spriteConfig) {
  389. return;
  390. }
  391. // 依次尝试常用尺寸键值
  392. const spritePath = spriteConfig['1x1'] || spriteConfig['1x2'] || spriteConfig['2x1'] || spriteConfig['2x2'];
  393. if (!spritePath) {
  394. return;
  395. }
  396. const framePath = `${spritePath}/spriteFrame`;
  397. resources.load(framePath, SpriteFrame, (err, spriteFrame) => {
  398. if (err) {
  399. return;
  400. }
  401. if (sprite && spriteFrame) {
  402. sprite.spriteFrame = spriteFrame;
  403. // === 缩小至原始尺寸的 0.5 倍 ===
  404. const uiTransform = sprite.node.getComponent(UITransform);
  405. if (uiTransform) {
  406. const originalSize = spriteFrame.originalSize || null;
  407. if (originalSize) {
  408. uiTransform.setContentSize(originalSize.width * 0.5, originalSize.height * 0.5);
  409. } else {
  410. // 若无法获取原尺寸,退化为缩放节点
  411. sprite.node.setScale(sprite.node.scale.x * 0.5, sprite.node.scale.y * 0.5, sprite.node.scale.z);
  412. }
  413. } else {
  414. // 没有 UITransform,直接缩放节点
  415. sprite.node.setScale(sprite.node.scale.x * 0.5, sprite.node.scale.y * 0.5, sprite.node.scale.z);
  416. }
  417. }
  418. });
  419. }
  420. /**
  421. * 静态:根据给定世界坐标,寻找最近的敌人节点
  422. */
  423. private static findNearestEnemyGlobal(worldPos: Vec3): Node | null {
  424. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  425. if (!enemyContainer) return null;
  426. const enemies = enemyContainer.children.filter(child => {
  427. if (!child.active) return false;
  428. const nameLower = child.name.toLowerCase();
  429. if (nameLower.includes('enemy') || nameLower.includes('敌人')) return true;
  430. if (child.getComponent('EnemyInstance')) return true;
  431. return false;
  432. });
  433. if (enemies.length === 0) return null;
  434. let nearest: Node = null;
  435. let nearestDist = Infinity;
  436. for (const enemy of enemies) {
  437. const dist = Vec3.distance(worldPos, enemy.worldPosition);
  438. if (dist < nearestDist) {
  439. nearestDist = dist;
  440. nearest = enemy;
  441. }
  442. }
  443. return nearest;
  444. }
  445. }