BulletLifecycle.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. // 穿透命中,继续飞行
  151. if (this.state.pierceLeft > 0) {
  152. this.state.pierceLeft--;
  153. console.log(`🪃 回旋镖穿透命中, 剩余穿透: ${this.state.pierceLeft}`);
  154. return false;
  155. }
  156. } else if (this.state.phase === 'returning') {
  157. // 返回途中命中,继续返回
  158. console.log('🪃 回旋镖返回途中命中');
  159. return false;
  160. }
  161. return false; // 回旋镖不会因为命中而销毁
  162. }
  163. /**
  164. * 处理目标撞击逻辑(导弹)
  165. */
  166. private handleTargetImpact(hitNode: Node): boolean {
  167. const isEnemy = this.isEnemyNode(hitNode);
  168. if (isEnemy) {
  169. console.log('🚀 导弹命中目标');
  170. this.state.shouldDestroy = true;
  171. return true;
  172. }
  173. // 如果不是敌人,继续飞行(导弹不会被其他物体阻挡)
  174. return false;
  175. }
  176. /**
  177. * 判断是否为地面节点
  178. */
  179. private isGroundNode(node: Node): boolean {
  180. const name = node.name.toLowerCase();
  181. return name.includes('ground') ||
  182. name.includes('wall') ||
  183. name.includes('地面') ||
  184. name.includes('墙');
  185. }
  186. /**
  187. * 判断是否为敌人节点
  188. */
  189. private isEnemyNode(node: Node): boolean {
  190. const name = node.name.toLowerCase();
  191. return name.includes('enemy') ||
  192. name.includes('敌人') ||
  193. node.getComponent('EnemyInstance') !== null;
  194. }
  195. update(dt: number) {
  196. if (!this.config || !this.state) return;
  197. this.state.elapsedTime += dt;
  198. // 更新飞行距离
  199. this.updateTravelDistance();
  200. // 检查各种销毁条件
  201. this.checkDestroyConditions();
  202. // 处理特殊逻辑
  203. this.updateSpecialLogic(dt);
  204. // 如果需要销毁,执行销毁
  205. if (this.state.shouldDestroy) {
  206. this.destroyBullet();
  207. }
  208. }
  209. /**
  210. * 更新飞行距离
  211. */
  212. private updateTravelDistance() {
  213. const currentPos = this.node.worldPosition;
  214. const distance = Vec3.distance(this.lastPosition, currentPos);
  215. this.state.travelDistance += distance;
  216. this.lastPosition.set(currentPos);
  217. }
  218. /**
  219. * 检查销毁条件
  220. */
  221. private checkDestroyConditions() {
  222. // 检查时间限制
  223. if (this.state.elapsedTime >= this.config.maxLifetime) {
  224. console.log('⏰ 子弹生存时间到期');
  225. this.state.shouldDestroy = true;
  226. return;
  227. }
  228. // 检查射程限制
  229. if (this.config.maxRange && this.state.travelDistance >= this.config.maxRange) {
  230. console.log(`📏 子弹超出射程限制: ${this.state.travelDistance}/${this.config.maxRange}`);
  231. if (this.config.type === 'return_trip' && this.state.phase === 'active') {
  232. // 回旋镖到达最远距离,开始返回
  233. this.startReturn();
  234. } else {
  235. this.state.shouldDestroy = true;
  236. }
  237. return;
  238. }
  239. // 检查越界
  240. if (this.checkOutOfBounds()) {
  241. console.log('🌍 子弹飞出游戏区域');
  242. this.state.shouldDestroy = true;
  243. return;
  244. }
  245. }
  246. /**
  247. * 更新特殊逻辑
  248. */
  249. private updateSpecialLogic(dt: number) {
  250. switch (this.config.type) {
  251. case 'return_trip':
  252. this.updateReturnTrip(dt);
  253. break;
  254. }
  255. }
  256. /**
  257. * 更新回旋镖逻辑
  258. */
  259. private updateReturnTrip(dt: number) {
  260. if (this.state.phase === 'active' && this.state.returnTimer > 0) {
  261. this.state.returnTimer -= dt;
  262. if (this.state.returnTimer <= 0) {
  263. this.startReturn();
  264. }
  265. } else if (this.state.phase === 'returning') {
  266. // 检查是否返回到原点
  267. const distanceToOrigin = Vec3.distance(this.node.worldPosition, this.state.startPosition);
  268. if (distanceToOrigin <= 50) { // 50单位的容差
  269. console.log('🪃 回旋镖返回原点');
  270. this.state.shouldDestroy = true;
  271. }
  272. }
  273. }
  274. /**
  275. * 开始返回
  276. */
  277. private startReturn() {
  278. console.log('🪃 回旋镖开始返回');
  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. const canvas = find('Canvas');
  291. if (!canvas) return false;
  292. const uiTransform = canvas.getComponent(UITransform);
  293. if (!uiTransform) return false;
  294. const halfWidth = uiTransform.width / 2;
  295. const halfHeight = uiTransform.height / 2;
  296. const center = canvas.worldPosition;
  297. const left = center.x - halfWidth;
  298. const right = center.x + halfWidth;
  299. const bottom = center.y - halfHeight;
  300. const top = center.y + halfHeight;
  301. // 允许一定的越界容差
  302. const margin = 200;
  303. const pos = this.node.worldPosition;
  304. return pos.x < left - margin || pos.x > right + margin ||
  305. pos.y < bottom - margin || pos.y > top + margin;
  306. }
  307. /**
  308. * 销毁子弹
  309. */
  310. private destroyBullet() {
  311. console.log('💀 子弹生命周期结束,销毁');
  312. this.node.destroy();
  313. }
  314. /**
  315. * 获取生命周期状态
  316. */
  317. public getState(): LifecycleState {
  318. return this.state;
  319. }
  320. /**
  321. * 检查是否应该销毁
  322. */
  323. public shouldDestroy(): boolean {
  324. return this.state ? this.state.shouldDestroy : true;
  325. }
  326. /**
  327. * 强制销毁
  328. */
  329. public forceDestroy() {
  330. this.state.shouldDestroy = true;
  331. }
  332. /**
  333. * 获取剩余生命时间
  334. */
  335. public getRemainingLifetime(): number {
  336. if (!this.config || !this.state) return 0;
  337. return Math.max(0, this.config.maxLifetime - this.state.elapsedTime);
  338. }
  339. /**
  340. * 验证配置
  341. */
  342. public static validateConfig(config: BulletLifecycleConfig): boolean {
  343. if (!config) return false;
  344. if (config.maxLifetime <= 0) return false;
  345. if (config.penetration < 0) return false;
  346. if (config.ricochetCount < 0) return false;
  347. if (config.maxRange && config.maxRange <= 0) return false;
  348. if (config.effectDuration && config.effectDuration < 0) return false;
  349. if (config.returnDelay && config.returnDelay < 0) return false;
  350. return true;
  351. }
  352. }