BulletLifecycle.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. import { _decorator, Component, Node, Vec3, Vec2, find, UITransform, RigidBody2D } from 'cc';
  2. import { BulletTrajectory } from './BulletTrajectory';
  3. import { BulletLifecycleConfig } from '../../Core/ConfigManager';
  4. const { ccclass, property } = _decorator;
  5. /**
  6. * 子弹生命周期控制器
  7. * 负责管理子弹的生存时间和销毁条件
  8. */
  9. export interface LifecycleState {
  10. elapsedTime: number; // 已存活时间
  11. hitCount: number; // 命中次数
  12. ricochetLeft: number; // 剩余弹射次数
  13. pierceLeft: number; // 剩余穿透次数
  14. travelDistance: number; // 已飞行距离
  15. phase: 'active' | 'returning' | 'effect' | 'destroyed'; // 生命周期阶段
  16. shouldDestroy: boolean; // 是否应该销毁
  17. startPosition: Vec3; // 起始位置
  18. returnTimer: number; // 返回计时器
  19. }
  20. @ccclass('BulletLifecycle')
  21. export class BulletLifecycle extends Component {
  22. private config: BulletLifecycleConfig = null;
  23. private state: LifecycleState = null;
  24. private lastPosition: Vec3 = new Vec3();
  25. /**
  26. * 初始化生命周期
  27. */
  28. public init(config: BulletLifecycleConfig, startPos: Vec3) {
  29. this.config = { ...config };
  30. this.state = {
  31. elapsedTime: 0,
  32. hitCount: 0,
  33. ricochetLeft: config.ricochetCount,
  34. pierceLeft: config.penetration,
  35. travelDistance: 0,
  36. phase: 'active',
  37. shouldDestroy: false,
  38. startPosition: startPos.clone(),
  39. returnTimer: config.returnDelay || 0
  40. };
  41. this.lastPosition = startPos.clone();
  42. }
  43. /**
  44. * 处理命中事件
  45. */
  46. public onHit(hitNode: Node): boolean {
  47. if (!this.config || !this.state) return true;
  48. this.state.hitCount++;
  49. switch (this.config.type) {
  50. case 'hit_destroy':
  51. return this.handleHitDestroy();
  52. case 'range_limit':
  53. return this.handleRangeLimit();
  54. case 'ricochet_counter':
  55. return this.handleRicochetCounter();
  56. case 'ground_impact':
  57. case 'ground_impact_with_effect':
  58. return this.handleGroundImpact(hitNode);
  59. case 'return_trip':
  60. return this.handleReturnTrip();
  61. case 'target_impact':
  62. return this.handleTargetImpact(hitNode);
  63. default:
  64. return true; // 默认销毁
  65. }
  66. }
  67. /**
  68. * 处理命中即销毁逻辑
  69. */
  70. private handleHitDestroy(): boolean {
  71. this.state.shouldDestroy = true;
  72. return true;
  73. }
  74. /**
  75. * 处理射程限制逻辑
  76. */
  77. private handleRangeLimit(): boolean {
  78. // 穿透逻辑
  79. if (this.state.pierceLeft > 0) {
  80. this.state.pierceLeft--;
  81. return false; // 不销毁,继续飞行
  82. } else {
  83. this.state.shouldDestroy = true;
  84. return true;
  85. }
  86. }
  87. /**
  88. * 处理弹射计数逻辑
  89. */
  90. private handleRicochetCounter(): boolean {
  91. console.log(`[BulletLifecycle] 弹射计数检查 - 剩余弹射次数: ${this.state.ricochetLeft}`);
  92. if (this.state.ricochetLeft > 0) {
  93. this.state.ricochetLeft--;
  94. console.log(`[BulletLifecycle] 弹射次数递减 - 剩余: ${this.state.ricochetLeft}`);
  95. // 弹射方向改变由BulletHitEffect处理,这里只管理生命周期
  96. return false; // 不销毁,继续弹射
  97. } else {
  98. console.log(`[BulletLifecycle] 弹射次数耗尽,标记销毁`);
  99. this.state.shouldDestroy = true;
  100. return true;
  101. }
  102. }
  103. /**
  104. * 处理地面撞击逻辑
  105. */
  106. private handleGroundImpact(hitNode: Node): boolean {
  107. const isGround = this.isGroundNode(hitNode);
  108. if (isGround) {
  109. // 进入效果阶段
  110. this.state.phase = 'effect';
  111. // 延迟销毁,等待效果结束
  112. if (this.config.effectDuration && this.config.effectDuration > 0) {
  113. this.scheduleOnce(() => {
  114. this.state.shouldDestroy = true;
  115. }, this.config.effectDuration);
  116. } else {
  117. this.state.shouldDestroy = true;
  118. }
  119. return true;
  120. } else {
  121. // === 立即冻结子弹运动,避免命中后继续绕圈 ===
  122. const trajectory = this.getComponent(BulletTrajectory);
  123. if (trajectory) {
  124. trajectory.enabled = false; // 停止后续 update
  125. }
  126. const rigidBody = this.getComponent(RigidBody2D);
  127. if (rigidBody) {
  128. rigidBody.linearVelocity = new Vec2(0, 0);
  129. rigidBody.angularVelocity = 0;
  130. }
  131. // 立即销毁,因为爆炸已经立即发生
  132. this.state.shouldDestroy = true;
  133. return true;
  134. }
  135. }
  136. /**
  137. * 处理回旋镖逻辑
  138. */
  139. private handleReturnTrip(): boolean {
  140. if (this.state.phase === 'active') {
  141. // 首次命中敌人立即开始返程
  142. console.log(`[BulletLifecycle] 回旋镖命中敌人,开始返回`);
  143. this.startReturn();
  144. return false; // 不销毁
  145. } else if (this.state.phase === 'returning') {
  146. // 返回途中命中,仅造成伤害不销毁
  147. console.log(`[BulletLifecycle] 回旋镖返回途中命中目标`);
  148. return false;
  149. }
  150. return false;
  151. }
  152. /**
  153. * 处理目标撞击逻辑(导弹)
  154. */
  155. private handleTargetImpact(hitNode: Node): boolean {
  156. const isEnemy = this.isEnemyNode(hitNode);
  157. if (isEnemy) {
  158. this.state.shouldDestroy = true;
  159. return true;
  160. }
  161. // 如果不是敌人,继续飞行(导弹不会被其他物体阻挡)
  162. return false;
  163. }
  164. /**
  165. * 判断是否为地面节点
  166. */
  167. private isGroundNode(node: Node): boolean {
  168. const name = node.name.toLowerCase();
  169. return name.includes('ground') ||
  170. name.includes('wall') ||
  171. name.includes('地面') ||
  172. name.includes('墙');
  173. }
  174. /**
  175. * 判断是否为敌人节点
  176. */
  177. private isEnemyNode(node: Node): boolean {
  178. // 检查是否为EnemySprite子节点
  179. if (node.name === 'EnemySprite' && node.parent) {
  180. return node.parent.getComponent('EnemyInstance') !== null;
  181. }
  182. // 兼容旧的敌人检测逻辑
  183. const name = node.name.toLowerCase();
  184. return name.includes('enemy') ||
  185. name.includes('敌人') ||
  186. node.getComponent('EnemyInstance') !== null;
  187. }
  188. update(dt: number) {
  189. if (!this.config || !this.state) {
  190. return;
  191. }
  192. this.state.elapsedTime += dt;
  193. // 更新飞行距离
  194. this.updateTravelDistance();
  195. // 检查各种销毁条件
  196. this.checkDestroyConditions();
  197. // 处理特殊逻辑
  198. this.updateSpecialLogic(dt);
  199. // 如果需要销毁,执行销毁
  200. if (this.state.shouldDestroy) {
  201. this.destroyBullet();
  202. }
  203. }
  204. /**
  205. * 更新飞行距离
  206. */
  207. private updateTravelDistance() {
  208. const currentPos = this.node.worldPosition;
  209. const distance = Vec3.distance(this.lastPosition, currentPos);
  210. this.state.travelDistance += distance;
  211. this.lastPosition.set(currentPos);
  212. }
  213. /**
  214. * 检查销毁条件
  215. */
  216. private checkDestroyConditions() {
  217. // 检查时间限制
  218. if (this.state.elapsedTime >= this.config.maxLifetime) {
  219. this.state.shouldDestroy = true;
  220. return;
  221. }
  222. // === 射程限制逻辑优化 ===
  223. if (this.config.maxRange && this.state.travelDistance >= this.config.maxRange) {
  224. if (this.config.type === 'range_limit') {
  225. this.state.shouldDestroy = true;
  226. } else if (this.config.type === 'return_trip') {
  227. // 回旋镖:首次超距时开始返回;返回途中不再因射程销毁
  228. if (this.state.phase === 'active') {
  229. console.log(`[BulletLifecycle] 回旋镖达到最大射程 ${this.config.maxRange},开始返回`);
  230. this.startReturn();
  231. }
  232. }
  233. // 其他生命周期类型忽略射程限制
  234. return;
  235. }
  236. // 检查越界
  237. const outOfBounds = this.checkOutOfBounds();
  238. if (outOfBounds) {
  239. if (this.config.type === 'return_trip' && this.state.phase === 'active') {
  240. this.startReturn();
  241. } else {
  242. this.state.shouldDestroy = true;
  243. }
  244. return;
  245. }
  246. }
  247. /**
  248. * 更新特殊逻辑
  249. */
  250. private updateSpecialLogic(dt: number) {
  251. switch (this.config.type) {
  252. case 'return_trip':
  253. this.updateReturnTrip(dt);
  254. break;
  255. }
  256. }
  257. /**
  258. * 更新回旋镖逻辑
  259. */
  260. private updateReturnTrip(dt: number) {
  261. if (this.state.phase === 'active') {
  262. // 检查返回计时器(如果配置了延迟返回)
  263. if (this.state.returnTimer > 0) {
  264. this.state.returnTimer -= dt;
  265. if (this.state.returnTimer <= 0) {
  266. console.log(`[BulletLifecycle] 回旋镖延迟时间到,开始返回`);
  267. this.startReturn();
  268. }
  269. }
  270. } else if (this.state.phase === 'returning') {
  271. // 检查是否返回到原点
  272. const distanceToOrigin = Vec3.distance(this.node.worldPosition, this.state.startPosition);
  273. if (distanceToOrigin <= 80) { // 增加容差到80单位,确保能够回收
  274. console.log(`[BulletLifecycle] 回旋镖返回到原点,销毁`);
  275. this.state.shouldDestroy = true;
  276. }
  277. }
  278. }
  279. /**
  280. * 开始返回
  281. */
  282. private startReturn() {
  283. if (this.state.phase === 'returning') {
  284. return; // 避免重复调用
  285. }
  286. this.state.phase = 'returning';
  287. console.log(`[BulletLifecycle] 回旋镖进入返回阶段`);
  288. const trajectory = this.getComponent(BulletTrajectory);
  289. if (trajectory) {
  290. // 设置返回目标为起始位置
  291. trajectory.setTargetPosition(this.state.startPosition);
  292. // 对于弧线弹道,不需要反转方向,让它自然转向回家
  293. // 只有非弧线弹道才需要反转方向
  294. const config = (trajectory as any).config;
  295. if (config && config.type !== 'arc') {
  296. trajectory.reverseDirection();
  297. }
  298. }
  299. }
  300. /**
  301. * 检查越界
  302. */
  303. private checkOutOfBounds(): boolean {
  304. // 优先使用 GameArea 的可视区域(若存在)
  305. const gameArea = find('Canvas/GameLevelUI/GameArea');
  306. let bounding = null;
  307. if (gameArea) {
  308. const tr = gameArea.getComponent(UITransform);
  309. if (tr) {
  310. bounding = tr.getBoundingBoxToWorld();
  311. }
  312. }
  313. // fallback => Canvas 整体区域
  314. if (!bounding) {
  315. const canvas = find('Canvas');
  316. if (canvas) {
  317. const tr = canvas.getComponent(UITransform);
  318. if (tr) {
  319. bounding = tr.getBoundingBoxToWorld();
  320. }
  321. }
  322. }
  323. // 若无法获取区域,则不做越界销毁
  324. if (!bounding) {
  325. return false;
  326. }
  327. // 允许一定的 margin
  328. const margin = 300; // 扩大容差,防止大速度时瞬移出界
  329. const pos = this.node.worldPosition;
  330. const outOfBounds = pos.x < bounding.xMin - margin ||
  331. pos.x > bounding.xMax + margin ||
  332. pos.y < bounding.yMin - margin ||
  333. pos.y > bounding.yMax + margin;
  334. return outOfBounds;
  335. }
  336. /**
  337. * 销毁子弹
  338. */
  339. private destroyBullet() {
  340. this.node.destroy();
  341. }
  342. /**
  343. * 获取生命周期状态
  344. */
  345. public getState(): LifecycleState {
  346. return this.state;
  347. }
  348. /**
  349. * 检查是否应该销毁
  350. */
  351. public shouldDestroy(): boolean {
  352. return this.state ? this.state.shouldDestroy : true;
  353. }
  354. /**
  355. * 强制销毁
  356. */
  357. public forceDestroy() {
  358. this.state.shouldDestroy = true;
  359. }
  360. /**
  361. * 获取剩余生命时间
  362. */
  363. public getRemainingLifetime(): number {
  364. if (!this.config || !this.state) return 0;
  365. return Math.max(0, this.config.maxLifetime - this.state.elapsedTime);
  366. }
  367. /**
  368. * 验证配置
  369. */
  370. public static validateConfig(config: BulletLifecycleConfig): boolean {
  371. if (!config) return false;
  372. if (config.maxLifetime <= 0) return false;
  373. if (config.penetration < 0) return false;
  374. if (config.ricochetCount < 0) return false;
  375. if (config.maxRange && config.maxRange <= 0) return false;
  376. if (config.effectDuration && config.effectDuration < 0) return false;
  377. if (config.returnDelay && config.returnDelay < 0) return false;
  378. return true;
  379. }
  380. }