WeaponBullet.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. // 若子弹在生成时与发射方块碰撞(位置重叠), 会立刻触发碰撞事件导致被销毁。
  188. // 因此在初始化完弹道后, 将子弹沿发射方向平移一小段距离(默认 30 像素左右)。
  189. const dir = (initData.direction || this.calculateDirection(initData.autoTarget)).clone().normalize();
  190. const spawnOffset = 30; // 可根据子弹半径或方块大小调整
  191. if (!Number.isNaN(dir.x) && !Number.isNaN(dir.y)) {
  192. const newLocalPos = this.node.position.clone().add(new Vec3(dir.x * spawnOffset, dir.y * spawnOffset, 0));
  193. this.node.setPosition(newLocalPos);
  194. }
  195. // 初始化命中效果组件
  196. this.bulletHitEffect = this.getComponent(BulletHitEffect) || this.addComponent(BulletHitEffect);
  197. this.bulletHitEffect.init(config.hitEffects);
  198. // 传递默认特效路径
  199. if (this.bulletHitEffect && config.visual) {
  200. (this.bulletHitEffect as any).setDefaultEffects?.(config.visual.hitEffect, config.visual.trailEffect, (config.visual as any).burnEffect);
  201. }
  202. // 初始化生命周期组件
  203. this.bulletLifecycle = this.getComponent(BulletLifecycle) || this.addComponent(BulletLifecycle);
  204. this.bulletLifecycle.init(config.lifecycle, initData.firePosition);
  205. console.log('生命周期穿透值 =', config.lifecycle.penetration);
  206. // 设置碰撞监听
  207. this.setupCollisionListener();
  208. this.isInitialized = true;
  209. console.log('✅ WeaponBullet 初始化完成');
  210. }
  211. /**
  212. * 设置物理组件
  213. */
  214. private setupPhysics() {
  215. const rigidBody = this.getComponent(RigidBody2D);
  216. if (rigidBody) {
  217. rigidBody.enabledContactListener = true;
  218. rigidBody.gravityScale = 0; // 由弹道组件控制重力
  219. rigidBody.linearDamping = 0;
  220. rigidBody.angularDamping = 0;
  221. rigidBody.allowSleep = false;
  222. }
  223. const collider = this.getComponent(Collider2D);
  224. if (collider) {
  225. collider.sensor = false;
  226. collider.on(Contact2DType.BEGIN_CONTACT, this.onHit, this);
  227. }
  228. console.log('✅ 物理组件设置完成');
  229. }
  230. /**
  231. * 计算子弹方向
  232. */
  233. private calculateDirection(autoTarget: boolean = false): Vec3 {
  234. if (!autoTarget) {
  235. // 随机方向
  236. const angle = Math.random() * Math.PI * 2;
  237. return new Vec3(Math.cos(angle), Math.sin(angle), 0);
  238. }
  239. // 寻找最近敌人
  240. const nearestEnemy = this.findNearestEnemy();
  241. if (nearestEnemy) {
  242. const direction = nearestEnemy.worldPosition.clone()
  243. .subtract(this.node.worldPosition)
  244. .normalize();
  245. console.log('🎯 自动瞄准最近敌人');
  246. return direction;
  247. }
  248. // 默认向右
  249. return new Vec3(1, 0, 0);
  250. }
  251. /**
  252. * 寻找最近敌人
  253. */
  254. private findNearestEnemy(): Node | null {
  255. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  256. if (!enemyContainer) return null;
  257. const enemies = enemyContainer.children.filter(child =>
  258. child.active && this.isEnemyNode(child)
  259. );
  260. if (enemies.length === 0) return null;
  261. let nearestEnemy: Node = null;
  262. let nearestDistance = Infinity;
  263. const bulletPos = this.node.worldPosition;
  264. for (const enemy of enemies) {
  265. const distance = Vec3.distance(bulletPos, enemy.worldPosition);
  266. if (distance < nearestDistance) {
  267. nearestDistance = distance;
  268. nearestEnemy = enemy;
  269. }
  270. }
  271. return nearestEnemy;
  272. }
  273. /**
  274. * 判断是否为敌人节点
  275. */
  276. private isEnemyNode(node: Node): boolean {
  277. const name = node.name.toLowerCase();
  278. return name.includes('enemy') ||
  279. name.includes('敌人') ||
  280. node.getComponent('EnemyInstance') !== null;
  281. }
  282. /**
  283. * 设置碰撞监听
  284. */
  285. private setupCollisionListener() {
  286. // 碰撞监听已在setupPhysics中设置
  287. }
  288. /**
  289. * 碰撞处理
  290. */
  291. private onHit(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  292. if (!this.isInitialized) return;
  293. const otherNode = otherCollider.node;
  294. console.log(`💥 子弹碰撞: ${otherNode.name}`);
  295. // 获取碰撞世界坐标
  296. let contactWorldPos: Vec3 = null;
  297. if (contact && (contact as any).getWorldManifold) {
  298. const wm = (contact as any).getWorldManifold();
  299. if (wm && wm.points && wm.points.length > 0) {
  300. contactWorldPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  301. }
  302. }
  303. if (!contactWorldPos) {
  304. contactWorldPos = otherNode.worldPosition.clone();
  305. }
  306. // 处理命中效果
  307. const hitResult: HitResult = this.bulletHitEffect.processHit(otherNode, contactWorldPos);
  308. // 通知生命周期组件发生命中(可能影响内部计数或阶段)
  309. if (this.bulletLifecycle) {
  310. this.bulletLifecycle.onHit(otherNode);
  311. }
  312. // 不直接销毁,交由 BulletLifecycle 自行处理
  313. // 生命周期和命中效果自行决定是否销毁;此处不再直接销毁,由 BulletLifecycle.update() 完成
  314. if (hitResult.shouldRicochet) {
  315. console.log('🎾 子弹发生弹射');
  316. } else if (hitResult.shouldContinue) {
  317. console.log('🏹 子弹继续飞行');
  318. }
  319. }
  320. update(dt: number) {
  321. // 生命周期检查由BulletLifecycle组件处理
  322. // 弹道更新由BulletTrajectory组件处理
  323. // 不需要在这里做额外处理
  324. }
  325. /**
  326. * 获取武器配置
  327. */
  328. public getWeaponConfig(): WeaponConfig {
  329. return this.weaponConfig;
  330. }
  331. /**
  332. * 获取子弹状态信息
  333. */
  334. public getBulletStatus() {
  335. return {
  336. isInitialized: this.isInitialized,
  337. weaponName: this.weaponConfig?.name,
  338. trajectoryState: this.bulletTrajectory?.getState(),
  339. lifecycleState: this.bulletLifecycle?.getState(),
  340. hitStats: this.bulletHitEffect?.getHitStats()
  341. };
  342. }
  343. /**
  344. * 强制销毁子弹
  345. */
  346. public forceDestroy() {
  347. if (this.bulletLifecycle) {
  348. this.bulletLifecycle.forceDestroy();
  349. }
  350. }
  351. /**
  352. * 验证初始化数据
  353. */
  354. public static validateInitData(initData: BulletInitData): boolean {
  355. if (!initData) return false;
  356. if (!initData.weaponId && !initData.weaponConfig) return false;
  357. if (!initData.firePosition) return false;
  358. return true;
  359. }
  360. onDestroy() {
  361. console.log('💀 WeaponBullet 被销毁');
  362. // 清理事件监听
  363. const collider = this.getComponent(Collider2D);
  364. if (collider) {
  365. collider.off(Contact2DType.BEGIN_CONTACT, this.onHit, this);
  366. }
  367. }
  368. }