WeaponBullet.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. import { _decorator, Component, Node, Vec2, Vec3, RigidBody2D, Collider2D, Contact2DType, IPhysics2DContact, find, Prefab, instantiate, UITransform, resources, sp, JsonAsset } 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. const { ccclass, property } = _decorator;
  7. /**
  8. * WeaponBullet - 重构后的统一子弹控制器
  9. *
  10. * 整合四个子模块:
  11. * 1. BulletCount - 子弹数量控制
  12. * 2. BulletTrajectory - 弹道控制
  13. * 3. BulletHitEffect - 命中效果(可叠加)
  14. * 4. BulletLifecycle - 生命周期控制
  15. *
  16. * 从weapons.json读取配置并分发给各模块
  17. */
  18. export interface WeaponConfig {
  19. id: string;
  20. name: string;
  21. bulletConfig: {
  22. count: BulletCountConfig;
  23. trajectory: BulletTrajectoryConfig;
  24. hitEffects: HitEffectConfig[];
  25. lifecycle: BulletLifecycleConfig;
  26. visual: {
  27. bulletPrefab: string;
  28. hitEffect: string;
  29. trailEffect?: string;
  30. muzzleFlash: string;
  31. };
  32. };
  33. stats: {
  34. damage: number;
  35. fireRate: number;
  36. range: number;
  37. bulletSpeed: number;
  38. accuracy: number;
  39. };
  40. }
  41. export interface BulletInitData {
  42. weaponId: string; // 武器ID,用于查找配置
  43. firePosition: Vec3; // 发射位置
  44. direction?: Vec3; // 发射方向(可选,自动瞄准时会自动计算)
  45. autoTarget?: boolean; // 是否自动瞄准
  46. weaponConfig?: WeaponConfig; // 直接传入的武器配置(优先级更高)
  47. }
  48. @ccclass('WeaponBullet')
  49. export class WeaponBullet extends Component {
  50. // === 子模块组件 ===
  51. private bulletTrajectory: BulletTrajectory = null;
  52. private bulletHitEffect: BulletHitEffect = null;
  53. private bulletLifecycle: BulletLifecycle = null;
  54. // === 配置数据 ===
  55. private weaponConfig: WeaponConfig = null;
  56. private isInitialized: boolean = false;
  57. // === 静态武器配置缓存 ===
  58. private static weaponsData: any = null;
  59. /**
  60. * 加载武器配置数据
  61. */
  62. public static loadWeaponsData(): Promise<void> {
  63. return new Promise((resolve, reject) => {
  64. if (WeaponBullet.weaponsData) {
  65. resolve();
  66. return;
  67. }
  68. resources.load('data/weapons', JsonAsset, (err, jsonAsset: JsonAsset) => {
  69. if (err) {
  70. console.error('❌ 加载武器配置失败:', err);
  71. reject(err);
  72. return;
  73. }
  74. WeaponBullet.weaponsData = jsonAsset.json;
  75. console.log('✅ 武器配置加载成功');
  76. resolve();
  77. });
  78. });
  79. }
  80. /**
  81. * 根据武器ID获取配置
  82. */
  83. public static getWeaponConfig(weaponId: string): WeaponConfig | null {
  84. if (!WeaponBullet.weaponsData) {
  85. console.error('❌ 武器配置未加载');
  86. return null;
  87. }
  88. const weapons = WeaponBullet.weaponsData.weapons;
  89. const weapon = weapons.find((w: any) => w.id === weaponId);
  90. if (!weapon) {
  91. console.error(`❌ 未找到武器配置: ${weaponId}`);
  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. console.error('❌ 无法获取武器配置');
  104. return [];
  105. }
  106. // 计算子弹生成信息
  107. const direction = initData.direction || new Vec3(1, 0, 0);
  108. const spawnInfos = BulletCount.calculateBulletSpawns(
  109. config.bulletConfig.count,
  110. initData.firePosition,
  111. direction
  112. );
  113. const bullets: Node[] = [];
  114. // 为每个子弹创建实例
  115. for (const spawnInfo of spawnInfos) {
  116. const createBullet = () => {
  117. const bullet = instantiate(bulletPrefab);
  118. const weaponBullet = bullet.getComponent(WeaponBullet) || bullet.addComponent(WeaponBullet);
  119. // 初始化子弹
  120. weaponBullet.init({
  121. ...initData,
  122. firePosition: spawnInfo.position,
  123. direction: spawnInfo.direction,
  124. weaponConfig: config
  125. });
  126. bullets.push(bullet);
  127. };
  128. // 处理延迟发射
  129. if (spawnInfo.delay > 0) {
  130. // 这里需要一个全局的调度器来处理延迟,暂时直接创建
  131. setTimeout(createBullet, spawnInfo.delay * 1000);
  132. } else {
  133. createBullet();
  134. }
  135. }
  136. return bullets;
  137. }
  138. /**
  139. * 初始化子弹
  140. */
  141. public init(initData: BulletInitData) {
  142. console.log('🚀 WeaponBullet 初始化开始...');
  143. // 获取武器配置
  144. this.weaponConfig = initData.weaponConfig || WeaponBullet.getWeaponConfig(initData.weaponId);
  145. if (!this.weaponConfig) {
  146. console.error('❌ 无法获取武器配置,初始化失败');
  147. return;
  148. }
  149. console.log(`🔫 初始化武器: ${this.weaponConfig.name}`);
  150. // 设置位置
  151. this.setPositionInGameArea(initData.firePosition);
  152. // 延迟初始化物理组件,确保位置设置完成
  153. this.scheduleOnce(() => {
  154. this.initializeComponents(initData);
  155. }, 0.05);
  156. }
  157. /**
  158. * 在GameArea中设置位置
  159. */
  160. private setPositionInGameArea(worldPos: Vec3) {
  161. const gameArea = find('Canvas/GameLevelUI/GameArea');
  162. if (gameArea) {
  163. const gameAreaTransform = gameArea.getComponent(UITransform);
  164. if (gameAreaTransform) {
  165. const localPos = gameAreaTransform.convertToNodeSpaceAR(worldPos);
  166. this.node.position = localPos;
  167. console.log('✅ 子弹位置已设置:', localPos);
  168. }
  169. }
  170. }
  171. /**
  172. * 初始化各个组件
  173. */
  174. private initializeComponents(initData: BulletInitData) {
  175. const config = this.weaponConfig.bulletConfig;
  176. // 确保物理组件存在
  177. this.setupPhysics();
  178. // 初始化弹道组件
  179. this.bulletTrajectory = this.getComponent(BulletTrajectory) || this.addComponent(BulletTrajectory);
  180. const trajCfg: BulletTrajectoryConfig = { ...config.trajectory, speed: this.weaponConfig.stats.bulletSpeed };
  181. this.bulletTrajectory.init(
  182. trajCfg,
  183. initData.direction || this.calculateDirection(initData.autoTarget),
  184. initData.firePosition
  185. );
  186. // 初始化命中效果组件
  187. this.bulletHitEffect = this.getComponent(BulletHitEffect) || this.addComponent(BulletHitEffect);
  188. this.bulletHitEffect.init(config.hitEffects);
  189. // 传递默认特效路径
  190. if (this.bulletHitEffect && config.visual) {
  191. (this.bulletHitEffect as any).setDefaultEffects?.(config.visual.hitEffect, config.visual.trailEffect, (config.visual as any).burnEffect);
  192. }
  193. // 初始化生命周期组件
  194. this.bulletLifecycle = this.getComponent(BulletLifecycle) || this.addComponent(BulletLifecycle);
  195. this.bulletLifecycle.init(config.lifecycle, initData.firePosition);
  196. // 设置碰撞监听
  197. this.setupCollisionListener();
  198. this.isInitialized = true;
  199. console.log('✅ WeaponBullet 初始化完成');
  200. }
  201. /**
  202. * 设置物理组件
  203. */
  204. private setupPhysics() {
  205. const rigidBody = this.getComponent(RigidBody2D);
  206. if (rigidBody) {
  207. rigidBody.enabledContactListener = true;
  208. rigidBody.gravityScale = 0; // 由弹道组件控制重力
  209. rigidBody.linearDamping = 0;
  210. rigidBody.angularDamping = 0;
  211. rigidBody.allowSleep = false;
  212. }
  213. const collider = this.getComponent(Collider2D);
  214. if (collider) {
  215. collider.sensor = false;
  216. collider.on(Contact2DType.BEGIN_CONTACT, this.onHit, this);
  217. }
  218. console.log('✅ 物理组件设置完成');
  219. }
  220. /**
  221. * 计算子弹方向
  222. */
  223. private calculateDirection(autoTarget: boolean = false): Vec3 {
  224. if (!autoTarget) {
  225. // 随机方向
  226. const angle = Math.random() * Math.PI * 2;
  227. return new Vec3(Math.cos(angle), Math.sin(angle), 0);
  228. }
  229. // 寻找最近敌人
  230. const nearestEnemy = this.findNearestEnemy();
  231. if (nearestEnemy) {
  232. const direction = nearestEnemy.worldPosition.clone()
  233. .subtract(this.node.worldPosition)
  234. .normalize();
  235. console.log('🎯 自动瞄准最近敌人');
  236. return direction;
  237. }
  238. // 默认向右
  239. return new Vec3(1, 0, 0);
  240. }
  241. /**
  242. * 寻找最近敌人
  243. */
  244. private findNearestEnemy(): Node | null {
  245. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  246. if (!enemyContainer) return null;
  247. const enemies = enemyContainer.children.filter(child =>
  248. child.active && this.isEnemyNode(child)
  249. );
  250. if (enemies.length === 0) return null;
  251. let nearestEnemy: Node = null;
  252. let nearestDistance = Infinity;
  253. const bulletPos = this.node.worldPosition;
  254. for (const enemy of enemies) {
  255. const distance = Vec3.distance(bulletPos, enemy.worldPosition);
  256. if (distance < nearestDistance) {
  257. nearestDistance = distance;
  258. nearestEnemy = enemy;
  259. }
  260. }
  261. return nearestEnemy;
  262. }
  263. /**
  264. * 判断是否为敌人节点
  265. */
  266. private isEnemyNode(node: Node): boolean {
  267. const name = node.name.toLowerCase();
  268. return name.includes('enemy') ||
  269. name.includes('敌人') ||
  270. node.getComponent('EnemyInstance') !== null;
  271. }
  272. /**
  273. * 设置碰撞监听
  274. */
  275. private setupCollisionListener() {
  276. // 碰撞监听已在setupPhysics中设置
  277. }
  278. /**
  279. * 碰撞处理
  280. */
  281. private onHit(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  282. if (!this.isInitialized) return;
  283. const otherNode = otherCollider.node;
  284. console.log(`💥 子弹碰撞: ${otherNode.name}`);
  285. // 获取碰撞世界坐标
  286. let contactWorldPos: Vec3 = null;
  287. if (contact && (contact as any).getWorldManifold) {
  288. const wm = (contact as any).getWorldManifold();
  289. if (wm && wm.points && wm.points.length > 0) {
  290. contactWorldPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  291. }
  292. }
  293. if (!contactWorldPos) {
  294. contactWorldPos = otherNode.worldPosition.clone();
  295. }
  296. // 处理命中效果
  297. const hitResult: HitResult = this.bulletHitEffect.processHit(otherNode, contactWorldPos);
  298. // 通知生命周期组件发生命中(可能影响内部计数或阶段)
  299. if (this.bulletLifecycle) {
  300. this.bulletLifecycle.onHit(otherNode);
  301. }
  302. // 不直接销毁,交由 BulletLifecycle 自行处理
  303. // 生命周期和命中效果自行决定是否销毁;此处不再直接销毁,由 BulletLifecycle.update() 完成
  304. if (hitResult.shouldRicochet) {
  305. console.log('🎾 子弹发生弹射');
  306. } else if (hitResult.shouldContinue) {
  307. console.log('🏹 子弹继续飞行');
  308. }
  309. }
  310. update(dt: number) {
  311. // 生命周期检查由BulletLifecycle组件处理
  312. // 弹道更新由BulletTrajectory组件处理
  313. // 不需要在这里做额外处理
  314. }
  315. /**
  316. * 获取武器配置
  317. */
  318. public getWeaponConfig(): WeaponConfig {
  319. return this.weaponConfig;
  320. }
  321. /**
  322. * 获取子弹状态信息
  323. */
  324. public getBulletStatus() {
  325. return {
  326. isInitialized: this.isInitialized,
  327. weaponName: this.weaponConfig?.name,
  328. trajectoryState: this.bulletTrajectory?.getState(),
  329. lifecycleState: this.bulletLifecycle?.getState(),
  330. hitStats: this.bulletHitEffect?.getHitStats()
  331. };
  332. }
  333. /**
  334. * 强制销毁子弹
  335. */
  336. public forceDestroy() {
  337. if (this.bulletLifecycle) {
  338. this.bulletLifecycle.forceDestroy();
  339. }
  340. }
  341. /**
  342. * 验证初始化数据
  343. */
  344. public static validateInitData(initData: BulletInitData): boolean {
  345. if (!initData) return false;
  346. if (!initData.weaponId && !initData.weaponConfig) return false;
  347. if (!initData.firePosition) return false;
  348. return true;
  349. }
  350. onDestroy() {
  351. console.log('💀 WeaponBullet 被销毁');
  352. // 清理事件监听
  353. const collider = this.getComponent(Collider2D);
  354. if (collider) {
  355. collider.off(Contact2DType.BEGIN_CONTACT, this.onHit, this);
  356. }
  357. }
  358. }