BulletTrajectory.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. @ccclass('BulletTrajectory')
  17. export class BulletTrajectory extends Component {
  18. private config: BulletTrajectoryConfig = null;
  19. private state: TrajectoryState = null;
  20. private rigidBody: RigidBody2D = null;
  21. private targetNode: Node = null;
  22. private homingTimer: number = 0;
  23. // === Arc Trajectory ===
  24. private arcDir: Vec3 = null; // 当前方向
  25. private arcTargetDir: Vec3 = null; // 目标方向(最终方向)
  26. /**
  27. * 初始化弹道
  28. */
  29. public init(config: BulletTrajectoryConfig, direction: Vec3, startPos: Vec3) {
  30. this.config = { ...config };
  31. this.rigidBody = this.getComponent(RigidBody2D);
  32. if (!this.rigidBody && config.type !== 'arc') {
  33. return;
  34. }
  35. // 初始化状态
  36. this.state = {
  37. initialVelocity: direction.clone().multiplyScalar(config.speed),
  38. currentVelocity: direction.clone().multiplyScalar(config.speed),
  39. startPosition: startPos.clone(),
  40. elapsedTime: 0,
  41. phase: 'launch'
  42. };
  43. this.homingTimer = config.homingDelay;
  44. // 设置初始速度
  45. this.applyInitialVelocity();
  46. // 寻找目标(用于追踪弹道)
  47. if (config.type === 'homing') {
  48. this.findTarget();
  49. }
  50. }
  51. /**
  52. * 设置初始速度
  53. */
  54. private applyInitialVelocity() {
  55. switch (this.config.type) {
  56. case 'straight':
  57. this.rigidBody.linearVelocity = new Vec2(
  58. this.state.initialVelocity.x,
  59. this.state.initialVelocity.y
  60. );
  61. break;
  62. case 'parabolic':
  63. // 计算抛物线初始速度
  64. const velocity = this.calculateParabolicVelocity();
  65. this.rigidBody.linearVelocity = velocity;
  66. this.state.currentVelocity.set(velocity.x, velocity.y, 0);
  67. break;
  68. case 'homing':
  69. this.rigidBody.linearVelocity = new Vec2(
  70. this.state.initialVelocity.x,
  71. this.state.initialVelocity.y
  72. );
  73. break;
  74. case 'arc':
  75. // 计算带 45° 随机偏移的初始方向
  76. const baseDir = this.state.initialVelocity.clone().normalize();
  77. const sign = Math.random() < 0.5 ? 1 : -1;
  78. const rad = 45 * Math.PI / 180 * sign;
  79. const cos = Math.cos(rad);
  80. const sin = Math.sin(rad);
  81. const offsetDir = new Vec3(
  82. baseDir.x * cos - baseDir.y * sin,
  83. baseDir.x * sin + baseDir.y * cos,
  84. 0
  85. ).normalize();
  86. this.arcDir = offsetDir;
  87. this.arcTargetDir = baseDir;
  88. // 如果有物理组件,则设置线速度;否则后续 updateArcTrajectory 将直接操作位移
  89. if (this.rigidBody) {
  90. this.rigidBody.linearVelocity = new Vec2(offsetDir.x * this.config.speed, offsetDir.y * this.config.speed);
  91. }
  92. // 保存当前速度
  93. this.state.currentVelocity.set(offsetDir.x * this.config.speed, offsetDir.y * this.config.speed, 0);
  94. break;
  95. }
  96. }
  97. /**
  98. * 计算抛物线初始速度
  99. */
  100. private calculateParabolicVelocity(): Vec2 {
  101. // NOTE:
  102. // 1. 当目标位于子弹正上/下方时, 原 direction 的 x 分量可能非常小甚至为 0, 导致 vx≈0, 子弹会几乎垂直运动, 看起来像"钢球"直落。
  103. // 2. 对于抛物线弹道, 我们总是希望子弹具备一个最小的水平速度, 并且保证初速度向上( vy>0 ),
  104. // 这样才能形成明显的抛物线效果并最终击中目标。
  105. const rawDir = this.state.initialVelocity.clone().normalize();
  106. // 单独提取水平方向, 忽略原始 y 分量, 以保证抛物线始终向前飞行
  107. const horizontalDir = new Vec3(rawDir.x, 0, 0);
  108. // 若水平方向过小, 取发射者面朝方向 (rawDir.x 的符号) 作为水平单位向量
  109. if (Math.abs(horizontalDir.x) < 0.01) {
  110. horizontalDir.x = rawDir.x >= 0 ? 1 : -1;
  111. }
  112. horizontalDir.normalize();
  113. const speed = this.config.speed;
  114. // 基础水平速度 (保持恒定, 不受重力影响)
  115. const vx = horizontalDir.x * speed;
  116. // 计算纵向初速度, 使得理论最高点接近 arcHeight
  117. // vy = sqrt(2 * g * h)
  118. const g = Math.max(0.1, Math.abs(this.config.gravity * 9.8)); // 避免 g=0 导致除0或 vy=0
  119. const desiredHeight = Math.max(1, 20); // 使用固定高度20作为默认抛物线高度
  120. let vy = Math.sqrt(2 * g * desiredHeight);
  121. // 如果原始方向有明显的向上分量, 为了兼容旧配置, 适当叠加
  122. if (rawDir.y > 0.1) {
  123. vy += rawDir.y * speed * 0.5; // 50% 叠加, 防止过高
  124. }
  125. return new Vec2(vx, vy);
  126. }
  127. /**
  128. * 寻找追踪目标
  129. */
  130. private findTarget() {
  131. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  132. if (!enemyContainer) return;
  133. const enemies = enemyContainer.children.filter(child =>
  134. child.active && this.isEnemyNode(child)
  135. );
  136. if (enemies.length === 0) return;
  137. // 寻找最近的敌人
  138. let nearestEnemy: Node = null;
  139. let nearestDistance = Infinity;
  140. const bulletPos = this.node.worldPosition;
  141. for (const enemy of enemies) {
  142. const distance = Vec3.distance(bulletPos, enemy.worldPosition);
  143. if (distance < nearestDistance) {
  144. nearestDistance = distance;
  145. nearestEnemy = enemy;
  146. }
  147. }
  148. if (nearestEnemy) {
  149. this.targetNode = nearestEnemy;
  150. this.state.targetPosition = nearestEnemy.worldPosition.clone();
  151. }
  152. }
  153. /**
  154. * 判断是否为敌人节点
  155. */
  156. private isEnemyNode(node: Node): boolean {
  157. // 检查是否为EnemySprite子节点
  158. if (node.name === 'EnemySprite' && node.parent) {
  159. return node.parent.getComponent('EnemyInstance') !== null;
  160. }
  161. // 兼容旧的敌人检测逻辑
  162. const name = node.name.toLowerCase();
  163. return name.includes('enemy') ||
  164. name.includes('敌人') ||
  165. node.getComponent('EnemyInstance') !== null;
  166. }
  167. update(dt: number) {
  168. if (!this.config || !this.state) return;
  169. this.state.elapsedTime += dt;
  170. switch (this.config.type) {
  171. case 'straight':
  172. this.updateStraightTrajectory(dt);
  173. break;
  174. case 'parabolic':
  175. this.updateParabolicTrajectory(dt);
  176. break;
  177. case 'homing':
  178. this.updateHomingTrajectory(dt);
  179. break;
  180. case 'arc':
  181. this.updateArcTrajectory(dt);
  182. break;
  183. }
  184. }
  185. /**
  186. * 更新直线弹道
  187. */
  188. private updateStraightTrajectory(dt: number) {
  189. // 直线弹道保持恒定速度,主要由物理引擎处理
  190. const currentVel = this.rigidBody.linearVelocity;
  191. const targetSpeed = this.config.speed;
  192. // 确保速度保持恒定
  193. const currentSpeed = Math.sqrt(currentVel.x * currentVel.x + currentVel.y * currentVel.y);
  194. if (Math.abs(currentSpeed - targetSpeed) > 1) {
  195. const direction = new Vec2(currentVel.x, currentVel.y).normalize();
  196. this.rigidBody.linearVelocity = direction.multiplyScalar(targetSpeed);
  197. }
  198. }
  199. /**
  200. * 更新抛物线弹道
  201. */
  202. private updateParabolicTrajectory(dt: number) {
  203. // 应用重力影响
  204. const currentVel = this.rigidBody.linearVelocity;
  205. const gravityForce = this.config.gravity * 9.8 * dt;
  206. this.rigidBody.linearVelocity = new Vec2(
  207. currentVel.x,
  208. currentVel.y - gravityForce
  209. );
  210. this.state.currentVelocity.set(currentVel.x, currentVel.y - gravityForce, 0);
  211. }
  212. /**
  213. * 更新追踪弹道
  214. */
  215. private updateHomingTrajectory(dt: number) {
  216. // 追踪延迟后开始追踪
  217. if (this.homingTimer > 0) {
  218. this.homingTimer -= dt;
  219. return;
  220. }
  221. // 确定追踪目标位置(敌人节点 or 返回点)
  222. let targetPos: Vec3 = null;
  223. if (this.state.phase === 'return' && this.state.targetPosition) {
  224. // 回程阶段,使用存储的返回坐标
  225. targetPos = this.state.targetPosition;
  226. } else {
  227. // 主动追踪敌人
  228. if (!this.targetNode || !this.targetNode.isValid) {
  229. this.findTarget();
  230. }
  231. if (this.targetNode && this.targetNode.isValid) {
  232. targetPos = this.targetNode.worldPosition;
  233. }
  234. }
  235. // 若依旧没有目标,直接退出
  236. if (!targetPos) {
  237. return;
  238. }
  239. // 计算追踪力
  240. const currentPos = this.node.worldPosition;
  241. const direction = targetPos.clone().subtract(currentPos).normalize();
  242. // 获取当前速度
  243. const currentVel = this.rigidBody.linearVelocity;
  244. const currentVelVec3 = new Vec3(currentVel.x, currentVel.y, 0);
  245. // 线性插值追踪
  246. const homingForce = this.config.homingStrength * dt * 10;
  247. const targetVelocity = direction.multiplyScalar(this.config.speed);
  248. const newVelocity = currentVelVec3.lerp(targetVelocity, homingForce);
  249. this.rigidBody.linearVelocity = new Vec2(newVelocity.x, newVelocity.y);
  250. this.state.currentVelocity.set(newVelocity);
  251. }
  252. /**
  253. * 更新弧线弹道
  254. */
  255. private updateArcTrajectory(dt: number) {
  256. if (!this.arcDir || !this.arcTargetDir) return;
  257. // === 动态追踪目标 ===
  258. // 若当前没有有效目标,则尝试重新寻找
  259. if (!this.targetNode || !this.targetNode.isValid) {
  260. this.findTarget();
  261. }
  262. // 检查是否到达目标位置(仅用于西瓜炸弹等爆炸武器,回旋镖不适用)
  263. const lifecycle = this.getComponent('BulletLifecycle') as any;
  264. const isBoomerang = lifecycle && lifecycle.getState && lifecycle.getState().phase !== undefined;
  265. if (this.state.targetPosition && !isBoomerang) {
  266. const currentPos = this.node.worldPosition;
  267. const distanceToTarget = Vec3.distance(currentPos, this.state.targetPosition);
  268. // 如果到达目标位置附近(50像素内),触发爆炸
  269. if (distanceToTarget <= 50) {
  270. // 停止运动
  271. if (this.rigidBody) {
  272. this.rigidBody.linearVelocity = new Vec2(0, 0);
  273. }
  274. // 先触发命中效果(包括音效播放)
  275. const hitEffect = this.getComponent('BulletHitEffect') as any;
  276. if (hitEffect && typeof hitEffect.processHit === 'function') {
  277. // 使用当前位置作为命中位置,传入子弹节点作为命中目标
  278. hitEffect.processHit(this.node, currentPos);
  279. }
  280. // 然后通知生命周期组件触发爆炸
  281. if (lifecycle && typeof lifecycle.onHit === 'function') {
  282. lifecycle.onHit(this.node); // 触发爆炸逻辑
  283. }
  284. return;
  285. }
  286. }
  287. // 根据回旋镖状态决定目标方向
  288. if (isBoomerang && lifecycle.getState().phase === 'returning') {
  289. // 返回阶段:朝向起始位置
  290. const pos = this.node.worldPosition;
  291. const startPos = this.state.startPosition || pos; // 防止空指针
  292. const dirToHome = startPos.clone().subtract(pos).normalize();
  293. this.arcTargetDir.set(dirToHome);
  294. // 更新目标位置为起始位置
  295. this.state.targetPosition = startPos.clone();
  296. } else {
  297. // 主动追踪阶段:朝向敌人
  298. if (this.targetNode && this.targetNode.isValid) {
  299. const pos = this.node.worldPosition;
  300. const dirToTarget = this.targetNode.worldPosition.clone().subtract(pos).normalize();
  301. this.arcTargetDir.set(dirToTarget);
  302. // 对于回旋镖,检查是否足够接近敌人来触发命中
  303. if (isBoomerang) {
  304. const distanceToEnemy = Vec3.distance(pos, this.targetNode.worldPosition);
  305. if (distanceToEnemy <= 30) { // 30像素内算命中
  306. // 触发命中效果
  307. const hitEffect = this.getComponent('BulletHitEffect') as any;
  308. if (hitEffect && typeof hitEffect.processHit === 'function') {
  309. hitEffect.processHit(this.targetNode, pos);
  310. }
  311. // 通知生命周期组件处理命中
  312. if (lifecycle && typeof lifecycle.onHit === 'function') {
  313. lifecycle.onHit(this.targetNode);
  314. }
  315. }
  316. }
  317. // 更新目标位置为当前敌人位置
  318. this.state.targetPosition = this.targetNode.worldPosition.clone();
  319. } else if (!this.state.targetPosition) {
  320. // 如果没有目标且没有记录的目标位置,设置一个默认的前方位置
  321. const defaultTarget = this.node.worldPosition.clone().add(this.arcDir.clone().multiplyScalar(200));
  322. this.state.targetPosition = defaultTarget;
  323. }
  324. }
  325. // 根据与目标距离动态调整转向速率:越近转得越快,避免打圈
  326. let rotateFactor = (this.config.rotateSpeed ?? 0.5) * dt;
  327. if (isBoomerang && lifecycle.getState().phase === 'returning') {
  328. // 回旋镖返回阶段:使用固定的转向速率,确保平滑返回
  329. rotateFactor *= 1.5; // 返回时适中的转向速率
  330. } else if (this.targetNode && this.targetNode.isValid) {
  331. // 主动追踪阶段:根据距离调整转向速率
  332. const distance = Vec3.distance(this.node.worldPosition, this.targetNode.worldPosition);
  333. rotateFactor *= (2000 / Math.max(distance, 50));
  334. }
  335. const newDir = new Vec3();
  336. Vec3.slerp(newDir, this.arcDir, this.arcTargetDir, Math.min(1, rotateFactor));
  337. this.arcDir.set(newDir);
  338. // 更新位移 / 速度
  339. if (this.rigidBody) {
  340. this.rigidBody.linearVelocity = new Vec2(this.arcDir.x * this.config.speed, this.arcDir.y * this.config.speed);
  341. } else {
  342. const displacement = this.arcDir.clone().multiplyScalar(this.config.speed * dt);
  343. this.node.worldPosition = this.node.worldPosition.add(displacement);
  344. }
  345. // 更新状态中的当前速度
  346. this.state.currentVelocity.set(this.arcDir.x * this.config.speed, this.arcDir.y * this.config.speed, 0);
  347. }
  348. /**
  349. * 获取当前速度
  350. */
  351. public getCurrentVelocity(): Vec3 {
  352. if (this.config?.type === 'arc') {
  353. return this.arcDir ? this.arcDir.clone().multiplyScalar(this.config.speed) : new Vec3();
  354. }
  355. const vel = this.rigidBody?.linearVelocity;
  356. if (!vel) return new Vec3();
  357. return new Vec3(vel.x, vel.y, 0);
  358. }
  359. /**
  360. * 获取弹道状态
  361. */
  362. public getState(): TrajectoryState {
  363. return this.state;
  364. }
  365. /**
  366. * 设置新的目标位置(用于回旋镖等)
  367. */
  368. public setTargetPosition(target: Vec3) {
  369. this.state.targetPosition = target.clone();
  370. }
  371. /**
  372. * 反转方向(用于回旋镖)
  373. */
  374. public reverseDirection() {
  375. const currentVel = this.rigidBody.linearVelocity;
  376. this.rigidBody.linearVelocity = new Vec2(-currentVel.x, -currentVel.y);
  377. this.state.currentVelocity.multiplyScalar(-1);
  378. this.state.phase = 'return';
  379. }
  380. /**
  381. * 改变方向(用于弹射)
  382. */
  383. public changeDirection(newDirection: Vec3) {
  384. // 归一化新方向
  385. const normalizedDir = newDirection.clone().normalize();
  386. // 保持当前速度大小
  387. const currentSpeed = this.config.speed;
  388. // 更新速度
  389. this.rigidBody.linearVelocity = new Vec2(
  390. normalizedDir.x * currentSpeed,
  391. normalizedDir.y * currentSpeed
  392. );
  393. // 更新状态
  394. this.state.currentVelocity.set(normalizedDir.x * currentSpeed, normalizedDir.y * currentSpeed, 0);
  395. }
  396. /**
  397. * 设置重力
  398. */
  399. public setGravity(gravity: number) {
  400. this.config.gravity = gravity;
  401. }
  402. /**
  403. * 验证配置
  404. */
  405. public static validateConfig(config: BulletTrajectoryConfig): boolean {
  406. if (!config) return false;
  407. if (config.speed <= 0) return false;
  408. if (config.gravity < 0) return false;
  409. if (config.homingStrength < 0 || config.homingStrength > 1) return false;
  410. if (config.homingDelay < 0) return false;
  411. if (config.rotateSpeed !== undefined && (config.rotateSpeed < 0 || config.rotateSpeed > 1)) return false;
  412. return true;
  413. }
  414. }