WeaponBullet.ts 19 KB

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