BulletTrajectory.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. import { _decorator, Component, Node, Vec2, Vec3, RigidBody2D, find } from 'cc';
  2. import { BulletTrajectoryConfig } from '../../Core/ConfigManager';
  3. const { ccclass, property } = _decorator;
  4. /**
  5. * 弹道控制器
  6. * 负责控制子弹的运动轨迹
  7. */
  8. export interface TrajectoryState {
  9. initialVelocity: Vec3; // 初始速度
  10. currentVelocity: Vec3; // 当前速度
  11. startPosition: Vec3; // 起始位置
  12. targetPosition?: Vec3; // 目标位置(追踪用)
  13. elapsedTime: number; // 经过时间
  14. phase: 'launch' | 'homing' | 'return'; // 运动阶段
  15. // 路径记录相关
  16. flightPath: Vec3[]; // 飞行路径记录
  17. pathRecordInterval: number; // 路径记录间隔(毫秒)
  18. lastRecordTime: number; // 上次记录时间
  19. returnPathIndex: number; // 返回路径索引
  20. // 发射源方块节点
  21. sourceBlock?: Node; // 发射源方块节点(用于动态获取返回位置)
  22. }
  23. @ccclass('BulletTrajectory')
  24. export class BulletTrajectory extends Component {
  25. private config: BulletTrajectoryConfig = null;
  26. private state: TrajectoryState = null;
  27. private rigidBody: RigidBody2D = null;
  28. private targetNode: Node = null;
  29. private homingTimer: number = 0;
  30. // === Arc Trajectory ===
  31. private arcDir: Vec3 = null; // 当前方向
  32. private arcTargetDir: Vec3 = null; // 目标方向(最终方向)
  33. /**
  34. * 初始化弹道
  35. */
  36. public init(config: BulletTrajectoryConfig, direction: Vec3, startPos: Vec3, sourceBlock?: Node) {
  37. this.config = { ...config };
  38. this.rigidBody = this.getComponent(RigidBody2D);
  39. if (!this.rigidBody && config.type !== 'arc') {
  40. return;
  41. }
  42. // 初始化状态
  43. this.state = {
  44. initialVelocity: direction.clone().multiplyScalar(config.speed),
  45. currentVelocity: direction.clone().multiplyScalar(config.speed),
  46. startPosition: startPos.clone(),
  47. elapsedTime: 0,
  48. phase: 'launch',
  49. // 路径记录初始化
  50. flightPath: [startPos.clone()],
  51. pathRecordInterval: 50, // 每50毫秒记录一次位置
  52. lastRecordTime: 0,
  53. returnPathIndex: -1,
  54. // 存储发射源方块节点
  55. sourceBlock: sourceBlock
  56. };
  57. this.homingTimer = config.homingDelay;
  58. // 设置初始速度
  59. this.applyInitialVelocity();
  60. // 寻找目标(用于追踪弹道)
  61. if (config.type === 'homing') {
  62. this.findTarget();
  63. }
  64. }
  65. /**
  66. * 设置初始速度
  67. */
  68. private applyInitialVelocity() {
  69. switch (this.config.type) {
  70. case 'straight':
  71. this.rigidBody.linearVelocity = new Vec2(
  72. this.state.initialVelocity.x,
  73. this.state.initialVelocity.y
  74. );
  75. break;
  76. case 'parabolic':
  77. // 计算抛物线初始速度
  78. const velocity = this.calculateParabolicVelocity();
  79. this.rigidBody.linearVelocity = velocity;
  80. this.state.currentVelocity.set(velocity.x, velocity.y, 0);
  81. break;
  82. case 'homing':
  83. this.rigidBody.linearVelocity = new Vec2(
  84. this.state.initialVelocity.x,
  85. this.state.initialVelocity.y
  86. );
  87. break;
  88. case 'arc':
  89. // 计算带 45° 随机偏移的初始方向
  90. const baseDir = this.state.initialVelocity.clone().normalize();
  91. const sign = Math.random() < 0.5 ? 1 : -1;
  92. const rad = 45 * Math.PI / 180 * sign;
  93. const cos = Math.cos(rad);
  94. const sin = Math.sin(rad);
  95. const offsetDir = new Vec3(
  96. baseDir.x * cos - baseDir.y * sin,
  97. baseDir.x * sin + baseDir.y * cos,
  98. 0
  99. ).normalize();
  100. this.arcDir = offsetDir;
  101. this.arcTargetDir = baseDir;
  102. // 如果有物理组件,则设置线速度;否则后续 updateArcTrajectory 将直接操作位移
  103. if (this.rigidBody) {
  104. this.rigidBody.linearVelocity = new Vec2(offsetDir.x * this.config.speed, offsetDir.y * this.config.speed);
  105. }
  106. // 保存当前速度
  107. this.state.currentVelocity.set(offsetDir.x * this.config.speed, offsetDir.y * this.config.speed, 0);
  108. break;
  109. }
  110. }
  111. /**
  112. * 计算抛物线初始速度
  113. */
  114. private calculateParabolicVelocity(): Vec2 {
  115. // NOTE:
  116. // 1. 当目标位于子弹正上/下方时, 原 direction 的 x 分量可能非常小甚至为 0, 导致 vx≈0, 子弹会几乎垂直运动, 看起来像"钢球"直落。
  117. // 2. 对于抛物线弹道, 我们总是希望子弹具备一个最小的水平速度, 并且保证初速度向上( vy>0 ),
  118. // 这样才能形成明显的抛物线效果并最终击中目标。
  119. const rawDir = this.state.initialVelocity.clone().normalize();
  120. // 单独提取水平方向, 忽略原始 y 分量, 以保证抛物线始终向前飞行
  121. const horizontalDir = new Vec3(rawDir.x, 0, 0);
  122. // 若水平方向过小, 取发射者面朝方向 (rawDir.x 的符号) 作为水平单位向量
  123. if (Math.abs(horizontalDir.x) < 0.01) {
  124. horizontalDir.x = rawDir.x >= 0 ? 1 : -1;
  125. }
  126. horizontalDir.normalize();
  127. const speed = this.config.speed;
  128. // 基础水平速度 (保持恒定, 不受重力影响)
  129. const vx = horizontalDir.x * speed;
  130. // 计算纵向初速度, 使得理论最高点接近 arcHeight
  131. // vy = sqrt(2 * g * h)
  132. const g = Math.max(0.1, Math.abs(this.config.gravity * 9.8)); // 避免 g=0 导致除0或 vy=0
  133. const desiredHeight = Math.max(1, 20); // 使用固定高度20作为默认抛物线高度
  134. let vy = Math.sqrt(2 * g * desiredHeight);
  135. // 如果原始方向有明显的向上分量, 为了兼容旧配置, 适当叠加
  136. if (rawDir.y > 0.1) {
  137. vy += rawDir.y * speed * 0.5; // 50% 叠加, 防止过高
  138. }
  139. return new Vec2(vx, vy);
  140. }
  141. /**
  142. * 寻找追踪目标
  143. */
  144. private findTarget() {
  145. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  146. if (!enemyContainer) return;
  147. const enemies = enemyContainer.children.filter(child =>
  148. child.active && this.isEnemyNode(child)
  149. );
  150. if (enemies.length === 0) return;
  151. // 寻找最近的敌人
  152. let nearestEnemy: Node = null;
  153. let nearestDistance = Infinity;
  154. const bulletPos = this.node.worldPosition;
  155. for (const enemy of enemies) {
  156. const distance = Vec3.distance(bulletPos, enemy.worldPosition);
  157. if (distance < nearestDistance) {
  158. nearestDistance = distance;
  159. nearestEnemy = enemy;
  160. }
  161. }
  162. if (nearestEnemy) {
  163. this.targetNode = nearestEnemy;
  164. this.state.targetPosition = nearestEnemy.worldPosition.clone();
  165. }
  166. }
  167. /**
  168. * 判断是否为敌人节点
  169. */
  170. private isEnemyNode(node: Node): boolean {
  171. // 检查是否为EnemySprite子节点
  172. if (node.name === 'EnemySprite' && node.parent) {
  173. return node.parent.getComponent('EnemyInstance') !== null;
  174. }
  175. // 兼容旧的敌人检测逻辑
  176. const name = node.name.toLowerCase();
  177. return name.includes('enemy') ||
  178. name.includes('敌人') ||
  179. node.getComponent('EnemyInstance') !== null;
  180. }
  181. update(dt: number) {
  182. if (!this.config || !this.state) return;
  183. this.state.elapsedTime += dt;
  184. // 记录路径(仅对回旋镖)
  185. this.recordFlightPath(dt);
  186. switch (this.config.type) {
  187. case 'straight':
  188. this.updateStraightTrajectory(dt);
  189. break;
  190. case 'parabolic':
  191. this.updateParabolicTrajectory(dt);
  192. break;
  193. case 'homing':
  194. this.updateHomingTrajectory(dt);
  195. break;
  196. case 'arc':
  197. this.updateArcTrajectory(dt);
  198. break;
  199. }
  200. }
  201. /**
  202. * 更新直线弹道
  203. */
  204. private updateStraightTrajectory(dt: number) {
  205. // 直线弹道保持恒定速度,主要由物理引擎处理
  206. const currentVel = this.rigidBody.linearVelocity;
  207. const targetSpeed = this.config.speed;
  208. // 确保速度保持恒定
  209. const currentSpeed = Math.sqrt(currentVel.x * currentVel.x + currentVel.y * currentVel.y);
  210. if (Math.abs(currentSpeed - targetSpeed) > 1) {
  211. const direction = new Vec2(currentVel.x, currentVel.y).normalize();
  212. this.rigidBody.linearVelocity = direction.multiplyScalar(targetSpeed);
  213. }
  214. }
  215. /**
  216. * 更新抛物线弹道
  217. */
  218. private updateParabolicTrajectory(dt: number) {
  219. // 应用重力影响
  220. const currentVel = this.rigidBody.linearVelocity;
  221. const gravityForce = this.config.gravity * 9.8 * dt;
  222. this.rigidBody.linearVelocity = new Vec2(
  223. currentVel.x,
  224. currentVel.y - gravityForce
  225. );
  226. this.state.currentVelocity.set(currentVel.x, currentVel.y - gravityForce, 0);
  227. }
  228. /**
  229. * 更新追踪弹道
  230. */
  231. private updateHomingTrajectory(dt: number) {
  232. // 追踪延迟后开始追踪
  233. if (this.homingTimer > 0) {
  234. this.homingTimer -= dt;
  235. return;
  236. }
  237. // 确定追踪目标位置(敌人节点 or 返回点)
  238. let targetPos: Vec3 = null;
  239. if (this.state.phase === 'return' && this.state.targetPosition) {
  240. // 回程阶段,使用存储的返回坐标
  241. targetPos = this.state.targetPosition;
  242. } else {
  243. // 主动追踪敌人
  244. if (!this.targetNode || !this.targetNode.isValid) {
  245. this.findTarget();
  246. }
  247. if (this.targetNode && this.targetNode.isValid) {
  248. targetPos = this.targetNode.worldPosition;
  249. }
  250. }
  251. // 若依旧没有目标,直接退出
  252. if (!targetPos) {
  253. return;
  254. }
  255. // 计算追踪力
  256. const currentPos = this.node.worldPosition;
  257. const direction = targetPos.clone().subtract(currentPos).normalize();
  258. // 获取当前速度
  259. const currentVel = this.rigidBody.linearVelocity;
  260. const currentVelVec3 = new Vec3(currentVel.x, currentVel.y, 0);
  261. // 线性插值追踪
  262. const homingForce = this.config.homingStrength * dt * 10;
  263. const targetVelocity = direction.multiplyScalar(this.config.speed);
  264. const newVelocity = currentVelVec3.lerp(targetVelocity, homingForce);
  265. this.rigidBody.linearVelocity = new Vec2(newVelocity.x, newVelocity.y);
  266. this.state.currentVelocity.set(newVelocity);
  267. }
  268. /**
  269. * 更新弧线弹道
  270. */
  271. private updateArcTrajectory(dt: number) {
  272. if (!this.arcDir || !this.arcTargetDir) return;
  273. // === 动态追踪目标 ===
  274. // 若当前没有有效目标,则尝试重新寻找
  275. if (!this.targetNode || !this.targetNode.isValid) {
  276. this.findTarget();
  277. }
  278. // 检查是否到达目标位置(爆炸武器和回旋镖都适用,但处理方式不同)
  279. const lifecycle = this.getComponent('BulletLifecycle') as any;
  280. const isBoomerang = lifecycle && lifecycle.getState && lifecycle.getState().phase !== undefined;
  281. if (this.state.targetPosition) {
  282. const currentPos = this.node.worldPosition;
  283. const distanceToTarget = Vec3.distance(currentPos, this.state.targetPosition);
  284. // 如果到达目标位置附近(50像素内)
  285. if (distanceToTarget <= 50) {
  286. if (isBoomerang) {
  287. // 回旋镖:触发命中效果但不爆炸,开始返回
  288. const hitEffect = this.getComponent('BulletHitEffect') as any;
  289. if (hitEffect && typeof hitEffect.processHit === 'function') {
  290. // 对目标位置附近的敌人造成伤害
  291. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  292. if (enemyContainer) {
  293. const enemies = enemyContainer.children.filter(child =>
  294. child.active && this.isEnemyNode(child)
  295. );
  296. // 寻找目标位置附近的敌人
  297. for (const enemy of enemies) {
  298. const distanceToEnemy = Vec3.distance(currentPos, enemy.worldPosition);
  299. if (distanceToEnemy <= 50) {
  300. hitEffect.processHit(enemy, currentPos);
  301. break; // 只命中一个敌人
  302. }
  303. }
  304. }
  305. }
  306. // 通知生命周期组件处理命中(回旋镖会开始返回而不是销毁)
  307. if (lifecycle && typeof lifecycle.onHit === 'function') {
  308. lifecycle.onHit(this.targetNode || this.node);
  309. }
  310. } else {
  311. // 爆炸武器:停止运动并触发爆炸
  312. if (this.rigidBody) {
  313. this.rigidBody.linearVelocity = new Vec2(0, 0);
  314. }
  315. // 先触发命中效果(包括音效播放)
  316. const hitEffect = this.getComponent('BulletHitEffect') as any;
  317. if (hitEffect && typeof hitEffect.processHit === 'function') {
  318. // 使用当前位置作为命中位置,传入子弹节点作为命中目标
  319. hitEffect.processHit(this.node, currentPos);
  320. }
  321. // 然后通知生命周期组件触发爆炸
  322. if (lifecycle && typeof lifecycle.onHit === 'function') {
  323. lifecycle.onHit(this.node); // 触发爆炸逻辑
  324. }
  325. return;
  326. }
  327. }
  328. }
  329. // 根据回旋镖状态决定目标方向
  330. if (isBoomerang && lifecycle.getState().phase === 'returning') {
  331. // 返回阶段:直接朝向目标位置(方块当前位置)
  332. if (this.state.targetPosition) {
  333. const pos = this.node.worldPosition;
  334. const dirToTarget = this.state.targetPosition.clone().subtract(pos).normalize();
  335. this.arcTargetDir.set(dirToTarget);
  336. // 检查是否到达目标位置
  337. const distanceToTarget = Vec3.distance(pos, this.state.targetPosition);
  338. if (distanceToTarget <= 30) {
  339. // 到达目标,销毁子弹
  340. if (lifecycle && typeof lifecycle.forceDestroy === 'function') {
  341. lifecycle.forceDestroy();
  342. }
  343. return;
  344. }
  345. }
  346. } else {
  347. // 主动追踪阶段:朝向敌人
  348. if (this.targetNode && this.targetNode.isValid) {
  349. const pos = this.node.worldPosition;
  350. const dirToTarget = this.targetNode.worldPosition.clone().subtract(pos).normalize();
  351. this.arcTargetDir.set(dirToTarget);
  352. // 对于回旋镖,检查是否足够接近敌人来触发命中
  353. if (isBoomerang) {
  354. const distanceToEnemy = Vec3.distance(pos, this.targetNode.worldPosition);
  355. if (distanceToEnemy <= 30) { // 30像素内算命中
  356. // 触发命中效果
  357. const hitEffect = this.getComponent('BulletHitEffect') as any;
  358. if (hitEffect && typeof hitEffect.processHit === 'function') {
  359. hitEffect.processHit(this.targetNode, pos);
  360. }
  361. // 通知生命周期组件处理命中
  362. if (lifecycle && typeof lifecycle.onHit === 'function') {
  363. lifecycle.onHit(this.targetNode);
  364. }
  365. }
  366. }
  367. // 更新目标位置为当前敌人位置
  368. this.state.targetPosition = this.targetNode.worldPosition.clone();
  369. } else if (!this.state.targetPosition) {
  370. // 如果没有目标且没有记录的目标位置,设置一个默认的前方位置
  371. const defaultTarget = this.node.worldPosition.clone().add(this.arcDir.clone().multiplyScalar(200));
  372. this.state.targetPosition = defaultTarget;
  373. }
  374. }
  375. // 根据与目标距离动态调整转向速率:越近转得越快,避免打圈
  376. let rotateFactor = (this.config.rotateSpeed ?? 0.5) * dt;
  377. if (isBoomerang && lifecycle.getState().phase === 'returning') {
  378. // 回旋镖返回阶段:根据距离调整转向速率,确保平滑返回
  379. if (this.state.targetPosition) {
  380. const distanceToTarget = Vec3.distance(this.node.worldPosition, this.state.targetPosition);
  381. // 根据距离动态调整转向速率,距离越近转向越快
  382. if (distanceToTarget < 50) {
  383. rotateFactor *= 4.0; // 非常接近目标点时快速转向
  384. } else if (distanceToTarget < 100) {
  385. rotateFactor *= 2.5; // 接近目标点时加快转向
  386. } else if (distanceToTarget < 200) {
  387. rotateFactor *= 1.8; // 中等距离时适度加快转向
  388. } else {
  389. rotateFactor *= 1.2; // 远距离时使用基础转向速率
  390. }
  391. }
  392. } else if (this.targetNode && this.targetNode.isValid) {
  393. // 主动追踪阶段:根据距离调整转向速率
  394. const distance = Vec3.distance(this.node.worldPosition, this.targetNode.worldPosition);
  395. rotateFactor *= (2000 / Math.max(distance, 50));
  396. }
  397. const newDir = new Vec3();
  398. Vec3.slerp(newDir, this.arcDir, this.arcTargetDir, Math.min(1, rotateFactor));
  399. this.arcDir.set(newDir);
  400. // 更新位移 / 速度
  401. if (this.rigidBody) {
  402. this.rigidBody.linearVelocity = new Vec2(this.arcDir.x * this.config.speed, this.arcDir.y * this.config.speed);
  403. } else {
  404. const displacement = this.arcDir.clone().multiplyScalar(this.config.speed * dt);
  405. this.node.worldPosition = this.node.worldPosition.add(displacement);
  406. }
  407. // 更新状态中的当前速度
  408. this.state.currentVelocity.set(this.arcDir.x * this.config.speed, this.arcDir.y * this.config.speed, 0);
  409. }
  410. /**
  411. * 获取当前速度
  412. */
  413. public getCurrentVelocity(): Vec3 {
  414. if (this.config?.type === 'arc') {
  415. return this.arcDir ? this.arcDir.clone().multiplyScalar(this.config.speed) : new Vec3();
  416. }
  417. const vel = this.rigidBody?.linearVelocity;
  418. if (!vel) return new Vec3();
  419. return new Vec3(vel.x, vel.y, 0);
  420. }
  421. /**
  422. * 获取弹道状态
  423. */
  424. public getState(): TrajectoryState {
  425. return this.state;
  426. }
  427. /**
  428. * 设置新的目标位置(用于回旋镖等)
  429. */
  430. public setTargetPosition(target: Vec3) {
  431. this.state.targetPosition = target.clone();
  432. }
  433. /**
  434. * 反转方向(用于回旋镖)
  435. */
  436. public reverseDirection() {
  437. const currentVel = this.rigidBody.linearVelocity;
  438. this.rigidBody.linearVelocity = new Vec2(-currentVel.x, -currentVel.y);
  439. this.state.currentVelocity.multiplyScalar(-1);
  440. this.state.phase = 'return';
  441. }
  442. /**
  443. * 改变方向(用于弹射)
  444. */
  445. public changeDirection(newDirection: Vec3) {
  446. // 归一化新方向
  447. const normalizedDir = newDirection.clone().normalize();
  448. // 保持当前速度大小
  449. const currentSpeed = this.config.speed;
  450. // 更新速度
  451. this.rigidBody.linearVelocity = new Vec2(
  452. normalizedDir.x * currentSpeed,
  453. normalizedDir.y * currentSpeed
  454. );
  455. // 更新状态
  456. this.state.currentVelocity.set(normalizedDir.x * currentSpeed, normalizedDir.y * currentSpeed, 0);
  457. }
  458. /**
  459. * 设置重力
  460. */
  461. public setGravity(gravity: number) {
  462. this.config.gravity = gravity;
  463. }
  464. /**
  465. * 记录飞行路径(仅对回旋镖)
  466. */
  467. private recordFlightPath(dt: number) {
  468. // 检查是否为回旋镖
  469. const lifecycle = this.getComponent('BulletLifecycle') as any;
  470. const isBoomerang = lifecycle && lifecycle.getState && lifecycle.getState().phase !== undefined;
  471. if (!isBoomerang) return;
  472. // 只在非返回阶段记录路径
  473. if (lifecycle.getState().phase === 'returning') return;
  474. // 检查是否到了记录时间
  475. this.state.lastRecordTime += dt * 1000; // 转换为毫秒
  476. if (this.state.lastRecordTime >= this.state.pathRecordInterval) {
  477. const currentPos = this.node.worldPosition.clone();
  478. // 避免记录重复位置
  479. const lastPos = this.state.flightPath[this.state.flightPath.length - 1];
  480. const distance = Vec3.distance(currentPos, lastPos);
  481. if (distance > 10) { // 只有移动距离超过10像素才记录
  482. this.state.flightPath.push(currentPos);
  483. this.state.lastRecordTime = 0;
  484. }
  485. }
  486. }
  487. /**
  488. * 获取返回路径中的下一个目标点
  489. */
  490. private getNextReturnTarget(): Vec3 | null {
  491. if (this.state.flightPath.length === 0) return null;
  492. // 如果还没有开始返回路径,初始化索引
  493. if (this.state.returnPathIndex === -1) {
  494. this.state.returnPathIndex = this.state.flightPath.length - 1;
  495. }
  496. // 检查当前位置是否接近目标点
  497. if (this.state.returnPathIndex >= 0) {
  498. const targetPos = this.state.flightPath[this.state.returnPathIndex];
  499. const currentPos = this.node.worldPosition;
  500. const distance = Vec3.distance(currentPos, targetPos);
  501. // 动态调整接近距离:路径点越少,接近距离越大,避免过于严格的路径跟随
  502. const approachDistance = Math.max(25, Math.min(50, 200 / this.state.flightPath.length));
  503. // 如果接近当前目标点,移动到下一个点
  504. if (distance <= approachDistance) {
  505. this.state.returnPathIndex--;
  506. }
  507. // 返回当前目标点,如果有多个路径点则进行平滑插值
  508. if (this.state.returnPathIndex >= 0) {
  509. const currentTarget = this.state.flightPath[this.state.returnPathIndex];
  510. // 如果还有下一个路径点,进行平滑插值
  511. if (this.state.returnPathIndex > 0) {
  512. const nextTarget = this.state.flightPath[this.state.returnPathIndex - 1];
  513. const progress = Math.min(1, (approachDistance - distance) / approachDistance);
  514. if (progress > 0) {
  515. // 在当前目标点和下一个目标点之间进行插值
  516. const smoothTarget = new Vec3();
  517. Vec3.lerp(smoothTarget, currentTarget, nextTarget, progress * 0.3);
  518. return smoothTarget;
  519. }
  520. }
  521. return currentTarget;
  522. }
  523. }
  524. // 如果已经遍历完所有路径点,返回发射源方块的当前位置
  525. if (this.state.sourceBlock && this.state.sourceBlock.isValid) {
  526. // 动态获取方块的当前世界位置
  527. return this.state.sourceBlock.worldPosition.clone();
  528. }
  529. // 如果方块节点无效,回退到起始位置
  530. return this.state.startPosition;
  531. }
  532. /**
  533. * 获取动态返回目标位置(方块当前位置)
  534. */
  535. public getDynamicReturnTarget(): Vec3 | null {
  536. if (this.state.sourceBlock && this.state.sourceBlock.isValid) {
  537. return this.state.sourceBlock.worldPosition.clone();
  538. }
  539. return null;
  540. }
  541. /**
  542. * 为返回阶段重新初始化轨道
  543. * @param currentPos 当前位置(新的发射点)
  544. * @param targetPos 目标位置(方块位置)
  545. */
  546. public reinitializeForReturn(currentPos: Vec3, targetPos: Vec3) {
  547. if (!this.config || !this.state) return;
  548. // 清除当前所有速度和运动
  549. if (this.rigidBody) {
  550. this.rigidBody.linearVelocity = new Vec2(0, 0);
  551. this.rigidBody.angularVelocity = 0;
  552. }
  553. // 计算从当前位置到目标位置的方向
  554. const direction = targetPos.clone().subtract(currentPos).normalize();
  555. // 重新设置状态
  556. this.state.startPosition = currentPos.clone();
  557. this.state.targetPosition = targetPos.clone();
  558. this.state.initialVelocity = direction.clone().multiplyScalar(this.config.speed);
  559. this.state.currentVelocity = direction.clone().multiplyScalar(this.config.speed);
  560. this.state.elapsedTime = 0;
  561. // 重新初始化弧线轨道参数
  562. if (this.config.type === 'arc') {
  563. this.arcDir = direction.clone();
  564. this.arcTargetDir = direction.clone();
  565. }
  566. // 清除路径记录,开始新的返回轨道
  567. this.state.flightPath = [currentPos.clone()];
  568. this.state.returnPathIndex = -1;
  569. this.state.lastRecordTime = 0;
  570. console.log(`[BulletTrajectory] 重新初始化返回轨道: ${currentPos} -> ${targetPos}`);
  571. }
  572. /**
  573. * 验证配置
  574. */
  575. public static validateConfig(config: BulletTrajectoryConfig): boolean {
  576. if (!config) return false;
  577. if (config.speed <= 0) return false;
  578. if (config.gravity < 0) return false;
  579. if (config.homingStrength < 0 || config.homingStrength > 1) return false;
  580. if (config.homingDelay < 0) return false;
  581. if (config.rotateSpeed !== undefined && (config.rotateSpeed < 0 || config.rotateSpeed > 1)) return false;
  582. return true;
  583. }
  584. }