BulletLifecycle.ts 14 KB

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