BulletLifecycle.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. import { _decorator, Component, Node, Vec3, find, UITransform } 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. }
  142. // 如果不是地面,按穿透逻辑处理
  143. return this.handleRangeLimit();
  144. }
  145. /**
  146. * 处理回旋镖逻辑
  147. */
  148. private handleReturnTrip(): boolean {
  149. if (this.state.phase === 'active') {
  150. // 首次命中立即开始返程,不再依据pierceLeft
  151. console.log('🪃 回旋镖命中敌人,开始返回');
  152. this.startReturn();
  153. return false; // 不销毁
  154. } else if (this.state.phase === 'returning') {
  155. // 返回途中命中,仅造成伤害不销毁
  156. return false;
  157. }
  158. return false;
  159. }
  160. /**
  161. * 处理目标撞击逻辑(导弹)
  162. */
  163. private handleTargetImpact(hitNode: Node): boolean {
  164. const isEnemy = this.isEnemyNode(hitNode);
  165. if (isEnemy) {
  166. console.log('🚀 导弹命中目标');
  167. this.state.shouldDestroy = true;
  168. return true;
  169. }
  170. // 如果不是敌人,继续飞行(导弹不会被其他物体阻挡)
  171. return false;
  172. }
  173. /**
  174. * 判断是否为地面节点
  175. */
  176. private isGroundNode(node: Node): boolean {
  177. const name = node.name.toLowerCase();
  178. return name.includes('ground') ||
  179. name.includes('wall') ||
  180. name.includes('地面') ||
  181. name.includes('墙');
  182. }
  183. /**
  184. * 判断是否为敌人节点
  185. */
  186. private isEnemyNode(node: Node): boolean {
  187. const name = node.name.toLowerCase();
  188. return name.includes('enemy') ||
  189. name.includes('敌人') ||
  190. node.getComponent('EnemyInstance') !== null;
  191. }
  192. update(dt: number) {
  193. if (!this.config || !this.state) return;
  194. this.state.elapsedTime += dt;
  195. // 更新飞行距离
  196. this.updateTravelDistance();
  197. // 检查各种销毁条件
  198. this.checkDestroyConditions();
  199. // 处理特殊逻辑
  200. this.updateSpecialLogic(dt);
  201. // 如果需要销毁,执行销毁
  202. if (this.state.shouldDestroy) {
  203. this.destroyBullet();
  204. }
  205. }
  206. /**
  207. * 更新飞行距离
  208. */
  209. private updateTravelDistance() {
  210. const currentPos = this.node.worldPosition;
  211. const distance = Vec3.distance(this.lastPosition, currentPos);
  212. this.state.travelDistance += distance;
  213. this.lastPosition.set(currentPos);
  214. }
  215. /**
  216. * 检查销毁条件
  217. */
  218. private checkDestroyConditions() {
  219. // 检查时间限制
  220. if (this.state.elapsedTime >= this.config.maxLifetime) {
  221. console.log('⏰ 子弹生存时间到期');
  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. // 仅当生命周期类型专门设为 range_limit 时才销毁
  229. console.log(`📏 子弹超出射程限制: ${this.state.travelDistance}/${this.config.maxRange}`);
  230. this.state.shouldDestroy = true;
  231. } else if (this.config.type === 'return_trip') {
  232. // 回旋镖:首次超距时开始返回;返回途中不再因射程销毁
  233. if (this.state.phase === 'active') {
  234. console.log(`📏 回旋镖到达最远距离(${this.config.maxRange}),开始返回`);
  235. this.startReturn();
  236. }
  237. }
  238. // 其他生命周期类型忽略射程限制
  239. return;
  240. }
  241. // 检查越界
  242. if (this.checkOutOfBounds()) {
  243. if (this.config.type === 'return_trip' && this.state.phase === 'active') {
  244. console.log('🌍 回旋镖飞到屏幕边界,开始返回');
  245. this.startReturn();
  246. } else {
  247. console.log('🌍 子弹飞出游戏区域');
  248. this.state.shouldDestroy = true;
  249. }
  250. return;
  251. }
  252. }
  253. /**
  254. * 更新特殊逻辑
  255. */
  256. private updateSpecialLogic(dt: number) {
  257. switch (this.config.type) {
  258. case 'return_trip':
  259. this.updateReturnTrip(dt);
  260. break;
  261. }
  262. }
  263. /**
  264. * 更新回旋镖逻辑
  265. */
  266. private updateReturnTrip(dt: number) {
  267. if (this.state.phase === 'active' && this.state.returnTimer > 0) {
  268. this.state.returnTimer -= dt;
  269. if (this.state.returnTimer <= 0) {
  270. this.startReturn();
  271. }
  272. } else if (this.state.phase === 'returning') {
  273. // 检查是否返回到原点
  274. const distanceToOrigin = Vec3.distance(this.node.worldPosition, this.state.startPosition);
  275. if (distanceToOrigin <= 50) { // 50单位的容差
  276. console.log('🪃 回旋镖返回原点');
  277. this.state.shouldDestroy = true;
  278. }
  279. }
  280. }
  281. /**
  282. * 开始返回
  283. */
  284. private startReturn() {
  285. console.log('🪃 回旋镖开始返回');
  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. }
  305. }
  306. // fallback => Canvas 整体区域
  307. if (!bounding) {
  308. const canvas = find('Canvas');
  309. if (canvas) {
  310. const tr = canvas.getComponent(UITransform);
  311. if (tr) {
  312. bounding = tr.getBoundingBoxToWorld();
  313. }
  314. }
  315. }
  316. // 若无法获取区域,则不做越界销毁
  317. if (!bounding) return false;
  318. // 允许一定的 margin
  319. const margin = 300; // 扩大容差,防止大速度时瞬移出界
  320. const pos = this.node.worldPosition;
  321. return pos.x < bounding.xMin - margin ||
  322. pos.x > bounding.xMax + margin ||
  323. pos.y < bounding.yMin - margin ||
  324. pos.y > bounding.yMax + margin;
  325. }
  326. /**
  327. * 销毁子弹
  328. */
  329. private destroyBullet() {
  330. console.log('💀 子弹生命周期结束,销毁');
  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. }