BulletLifecycle.ts 12 KB

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