BulletLifecycle.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. // 延迟销毁,确保爆炸的 0.1 s 延迟能正常触发
  122. this.scheduleOnce(() => {
  123. this.state.shouldDestroy = true;
  124. }, 0.2);
  125. // === 立即冻结子弹运动,避免命中后继续绕圈 ===
  126. const trajectory = this.getComponent(BulletTrajectory);
  127. if (trajectory) {
  128. trajectory.enabled = false; // 停止后续 update
  129. }
  130. const rigidBody = this.getComponent(RigidBody2D);
  131. if (rigidBody) {
  132. rigidBody.linearVelocity = new Vec2(0, 0);
  133. rigidBody.angularVelocity = 0;
  134. }
  135. return true;
  136. }
  137. }
  138. /**
  139. * 处理回旋镖逻辑
  140. */
  141. private handleReturnTrip(): boolean {
  142. if (this.state.phase === 'active') {
  143. // 首次命中敌人立即开始返程
  144. console.log(`[BulletLifecycle] 回旋镖命中敌人,开始返回`);
  145. this.startReturn();
  146. return false; // 不销毁
  147. } else if (this.state.phase === 'returning') {
  148. // 返回途中命中,仅造成伤害不销毁
  149. console.log(`[BulletLifecycle] 回旋镖返回途中命中目标`);
  150. return false;
  151. }
  152. return false;
  153. }
  154. /**
  155. * 处理目标撞击逻辑(导弹)
  156. */
  157. private handleTargetImpact(hitNode: Node): boolean {
  158. const isEnemy = this.isEnemyNode(hitNode);
  159. if (isEnemy) {
  160. this.state.shouldDestroy = true;
  161. return true;
  162. }
  163. // 如果不是敌人,继续飞行(导弹不会被其他物体阻挡)
  164. return false;
  165. }
  166. /**
  167. * 判断是否为地面节点
  168. */
  169. private isGroundNode(node: Node): boolean {
  170. const name = node.name.toLowerCase();
  171. return name.includes('ground') ||
  172. name.includes('wall') ||
  173. name.includes('地面') ||
  174. name.includes('墙');
  175. }
  176. /**
  177. * 判断是否为敌人节点
  178. */
  179. private isEnemyNode(node: Node): boolean {
  180. const name = node.name.toLowerCase();
  181. return name.includes('enemy') ||
  182. name.includes('敌人') ||
  183. node.getComponent('EnemyInstance') !== null;
  184. }
  185. update(dt: number) {
  186. if (!this.config || !this.state) {
  187. return;
  188. }
  189. this.state.elapsedTime += dt;
  190. // 更新飞行距离
  191. this.updateTravelDistance();
  192. // 检查各种销毁条件
  193. this.checkDestroyConditions();
  194. // 处理特殊逻辑
  195. this.updateSpecialLogic(dt);
  196. // 如果需要销毁,执行销毁
  197. if (this.state.shouldDestroy) {
  198. this.destroyBullet();
  199. }
  200. }
  201. /**
  202. * 更新飞行距离
  203. */
  204. private updateTravelDistance() {
  205. const currentPos = this.node.worldPosition;
  206. const distance = Vec3.distance(this.lastPosition, currentPos);
  207. this.state.travelDistance += distance;
  208. this.lastPosition.set(currentPos);
  209. }
  210. /**
  211. * 检查销毁条件
  212. */
  213. private checkDestroyConditions() {
  214. // 检查时间限制
  215. if (this.state.elapsedTime >= this.config.maxLifetime) {
  216. this.state.shouldDestroy = true;
  217. return;
  218. }
  219. // === 射程限制逻辑优化 ===
  220. if (this.config.maxRange && this.state.travelDistance >= this.config.maxRange) {
  221. if (this.config.type === 'range_limit') {
  222. this.state.shouldDestroy = true;
  223. } else if (this.config.type === 'return_trip') {
  224. // 回旋镖:首次超距时开始返回;返回途中不再因射程销毁
  225. if (this.state.phase === 'active') {
  226. console.log(`[BulletLifecycle] 回旋镖达到最大射程 ${this.config.maxRange},开始返回`);
  227. this.startReturn();
  228. }
  229. }
  230. // 其他生命周期类型忽略射程限制
  231. return;
  232. }
  233. // 检查越界
  234. const outOfBounds = this.checkOutOfBounds();
  235. if (outOfBounds) {
  236. if (this.config.type === 'return_trip' && this.state.phase === 'active') {
  237. this.startReturn();
  238. } else {
  239. this.state.shouldDestroy = true;
  240. }
  241. return;
  242. }
  243. }
  244. /**
  245. * 更新特殊逻辑
  246. */
  247. private updateSpecialLogic(dt: number) {
  248. switch (this.config.type) {
  249. case 'return_trip':
  250. this.updateReturnTrip(dt);
  251. break;
  252. }
  253. }
  254. /**
  255. * 更新回旋镖逻辑
  256. */
  257. private updateReturnTrip(dt: number) {
  258. if (this.state.phase === 'active') {
  259. // 检查返回计时器(如果配置了延迟返回)
  260. if (this.state.returnTimer > 0) {
  261. this.state.returnTimer -= dt;
  262. if (this.state.returnTimer <= 0) {
  263. console.log(`[BulletLifecycle] 回旋镖延迟时间到,开始返回`);
  264. this.startReturn();
  265. }
  266. }
  267. } else if (this.state.phase === 'returning') {
  268. // 检查是否返回到原点
  269. const distanceToOrigin = Vec3.distance(this.node.worldPosition, this.state.startPosition);
  270. if (distanceToOrigin <= 80) { // 增加容差到80单位,确保能够回收
  271. console.log(`[BulletLifecycle] 回旋镖返回到原点,销毁`);
  272. this.state.shouldDestroy = true;
  273. }
  274. }
  275. }
  276. /**
  277. * 开始返回
  278. */
  279. private startReturn() {
  280. if (this.state.phase === 'returning') {
  281. return; // 避免重复调用
  282. }
  283. this.state.phase = 'returning';
  284. console.log(`[BulletLifecycle] 回旋镖进入返回阶段`);
  285. const trajectory = this.getComponent(BulletTrajectory);
  286. if (trajectory) {
  287. // 设置返回目标为起始位置
  288. trajectory.setTargetPosition(this.state.startPosition);
  289. // 对于弧线弹道,不需要反转方向,让它自然转向回家
  290. // 只有非弧线弹道才需要反转方向
  291. const config = (trajectory as any).config;
  292. if (config && config.type !== 'arc') {
  293. trajectory.reverseDirection();
  294. }
  295. }
  296. }
  297. /**
  298. * 检查越界
  299. */
  300. private checkOutOfBounds(): boolean {
  301. // 优先使用 GameArea 的可视区域(若存在)
  302. const gameArea = find('Canvas/GameLevelUI/GameArea');
  303. let bounding = null;
  304. if (gameArea) {
  305. const tr = gameArea.getComponent(UITransform);
  306. if (tr) {
  307. bounding = tr.getBoundingBoxToWorld();
  308. }
  309. }
  310. // fallback => Canvas 整体区域
  311. if (!bounding) {
  312. const canvas = find('Canvas');
  313. if (canvas) {
  314. const tr = canvas.getComponent(UITransform);
  315. if (tr) {
  316. bounding = tr.getBoundingBoxToWorld();
  317. }
  318. }
  319. }
  320. // 若无法获取区域,则不做越界销毁
  321. if (!bounding) {
  322. return false;
  323. }
  324. // 允许一定的 margin
  325. const margin = 300; // 扩大容差,防止大速度时瞬移出界
  326. const pos = this.node.worldPosition;
  327. const outOfBounds = pos.x < bounding.xMin - margin ||
  328. pos.x > bounding.xMax + margin ||
  329. pos.y < bounding.yMin - margin ||
  330. pos.y > bounding.yMax + margin;
  331. return outOfBounds;
  332. }
  333. /**
  334. * 销毁子弹
  335. */
  336. private destroyBullet() {
  337. this.node.destroy();
  338. }
  339. /**
  340. * 获取生命周期状态
  341. */
  342. public getState(): LifecycleState {
  343. return this.state;
  344. }
  345. /**
  346. * 检查是否应该销毁
  347. */
  348. public shouldDestroy(): boolean {
  349. return this.state ? this.state.shouldDestroy : true;
  350. }
  351. /**
  352. * 强制销毁
  353. */
  354. public forceDestroy() {
  355. this.state.shouldDestroy = true;
  356. }
  357. /**
  358. * 获取剩余生命时间
  359. */
  360. public getRemainingLifetime(): number {
  361. if (!this.config || !this.state) return 0;
  362. return Math.max(0, this.config.maxLifetime - this.state.elapsedTime);
  363. }
  364. /**
  365. * 验证配置
  366. */
  367. public static validateConfig(config: BulletLifecycleConfig): boolean {
  368. if (!config) return false;
  369. if (config.maxLifetime <= 0) return false;
  370. if (config.penetration < 0) return false;
  371. if (config.ricochetCount < 0) return false;
  372. if (config.maxRange && config.maxRange <= 0) return false;
  373. if (config.effectDuration && config.effectDuration < 0) return false;
  374. if (config.returnDelay && config.returnDelay < 0) return false;
  375. return true;
  376. }
  377. }