BulletLifecycle.ts 16 KB

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