BulletLifecycle.ts 13 KB

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