BulletLifecycle.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. // 首次命中立即开始返程,不再依据pierceLeft
  144. this.startReturn();
  145. return false; // 不销毁
  146. } else if (this.state.phase === 'returning') {
  147. // 返回途中命中,仅造成伤害不销毁
  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. const name = node.name.toLowerCase();
  179. return name.includes('enemy') ||
  180. name.includes('敌人') ||
  181. node.getComponent('EnemyInstance') !== null;
  182. }
  183. update(dt: number) {
  184. if (!this.config || !this.state) {
  185. return;
  186. }
  187. this.state.elapsedTime += dt;
  188. // 更新飞行距离
  189. this.updateTravelDistance();
  190. // 检查各种销毁条件
  191. this.checkDestroyConditions();
  192. // 处理特殊逻辑
  193. this.updateSpecialLogic(dt);
  194. // 如果需要销毁,执行销毁
  195. if (this.state.shouldDestroy) {
  196. this.destroyBullet();
  197. }
  198. }
  199. /**
  200. * 更新飞行距离
  201. */
  202. private updateTravelDistance() {
  203. const currentPos = this.node.worldPosition;
  204. const distance = Vec3.distance(this.lastPosition, currentPos);
  205. this.state.travelDistance += distance;
  206. this.lastPosition.set(currentPos);
  207. }
  208. /**
  209. * 检查销毁条件
  210. */
  211. private checkDestroyConditions() {
  212. // 检查时间限制
  213. if (this.state.elapsedTime >= this.config.maxLifetime) {
  214. this.state.shouldDestroy = true;
  215. return;
  216. }
  217. // === 射程限制逻辑优化 ===
  218. if (this.config.maxRange && this.state.travelDistance >= this.config.maxRange) {
  219. if (this.config.type === 'range_limit') {
  220. this.state.shouldDestroy = true;
  221. } else if (this.config.type === 'return_trip') {
  222. // 回旋镖:首次超距时开始返回;返回途中不再因射程销毁
  223. if (this.state.phase === 'active') {
  224. this.startReturn();
  225. }
  226. }
  227. // 其他生命周期类型忽略射程限制
  228. return;
  229. }
  230. // 检查越界
  231. const outOfBounds = this.checkOutOfBounds();
  232. if (outOfBounds) {
  233. if (this.config.type === 'return_trip' && this.state.phase === 'active') {
  234. this.startReturn();
  235. } else {
  236. this.state.shouldDestroy = true;
  237. }
  238. return;
  239. }
  240. }
  241. /**
  242. * 更新特殊逻辑
  243. */
  244. private updateSpecialLogic(dt: number) {
  245. switch (this.config.type) {
  246. case 'return_trip':
  247. this.updateReturnTrip(dt);
  248. break;
  249. }
  250. }
  251. /**
  252. * 更新回旋镖逻辑
  253. */
  254. private updateReturnTrip(dt: number) {
  255. if (this.state.phase === 'active' && this.state.returnTimer > 0) {
  256. this.state.returnTimer -= dt;
  257. if (this.state.returnTimer <= 0) {
  258. this.startReturn();
  259. }
  260. } else if (this.state.phase === 'returning') {
  261. // 检查是否返回到原点
  262. const distanceToOrigin = Vec3.distance(this.node.worldPosition, this.state.startPosition);
  263. if (distanceToOrigin <= 50) { // 50单位的容差
  264. this.state.shouldDestroy = true;
  265. }
  266. }
  267. }
  268. /**
  269. * 开始返回
  270. */
  271. private startReturn() {
  272. this.state.phase = 'returning';
  273. const trajectory = this.getComponent(BulletTrajectory);
  274. if (trajectory) {
  275. trajectory.setTargetPosition(this.state.startPosition);
  276. trajectory.reverseDirection();
  277. }
  278. }
  279. /**
  280. * 检查越界
  281. */
  282. private checkOutOfBounds(): boolean {
  283. // 优先使用 GameArea 的可视区域(若存在)
  284. const gameArea = find('Canvas/GameLevelUI/GameArea');
  285. let bounding = null;
  286. if (gameArea) {
  287. const tr = gameArea.getComponent(UITransform);
  288. if (tr) {
  289. bounding = tr.getBoundingBoxToWorld();
  290. }
  291. }
  292. // fallback => Canvas 整体区域
  293. if (!bounding) {
  294. const canvas = find('Canvas');
  295. if (canvas) {
  296. const tr = canvas.getComponent(UITransform);
  297. if (tr) {
  298. bounding = tr.getBoundingBoxToWorld();
  299. }
  300. }
  301. }
  302. // 若无法获取区域,则不做越界销毁
  303. if (!bounding) {
  304. return false;
  305. }
  306. // 允许一定的 margin
  307. const margin = 300; // 扩大容差,防止大速度时瞬移出界
  308. const pos = this.node.worldPosition;
  309. const outOfBounds = pos.x < bounding.xMin - margin ||
  310. pos.x > bounding.xMax + margin ||
  311. pos.y < bounding.yMin - margin ||
  312. pos.y > bounding.yMax + margin;
  313. return outOfBounds;
  314. }
  315. /**
  316. * 销毁子弹
  317. */
  318. private destroyBullet() {
  319. this.node.destroy();
  320. }
  321. /**
  322. * 获取生命周期状态
  323. */
  324. public getState(): LifecycleState {
  325. return this.state;
  326. }
  327. /**
  328. * 检查是否应该销毁
  329. */
  330. public shouldDestroy(): boolean {
  331. return this.state ? this.state.shouldDestroy : true;
  332. }
  333. /**
  334. * 强制销毁
  335. */
  336. public forceDestroy() {
  337. this.state.shouldDestroy = true;
  338. }
  339. /**
  340. * 获取剩余生命时间
  341. */
  342. public getRemainingLifetime(): number {
  343. if (!this.config || !this.state) return 0;
  344. return Math.max(0, this.config.maxLifetime - this.state.elapsedTime);
  345. }
  346. /**
  347. * 验证配置
  348. */
  349. public static validateConfig(config: BulletLifecycleConfig): boolean {
  350. if (!config) return false;
  351. if (config.maxLifetime <= 0) return false;
  352. if (config.penetration < 0) return false;
  353. if (config.ricochetCount < 0) return false;
  354. if (config.maxRange && config.maxRange <= 0) return false;
  355. if (config.effectDuration && config.effectDuration < 0) return false;
  356. if (config.returnDelay && config.returnDelay < 0) return false;
  357. return true;
  358. }
  359. }