BulletLifecycle.ts 14 KB

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