BulletTrajectory.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. const name = node.name.toLowerCase();
  158. return name.includes('enemy') ||
  159. name.includes('敌人') ||
  160. node.getComponent('EnemyInstance') !== null;
  161. }
  162. update(dt: number) {
  163. if (!this.config || !this.state) return;
  164. this.state.elapsedTime += dt;
  165. switch (this.config.type) {
  166. case 'straight':
  167. this.updateStraightTrajectory(dt);
  168. break;
  169. case 'parabolic':
  170. this.updateParabolicTrajectory(dt);
  171. break;
  172. case 'homing':
  173. this.updateHomingTrajectory(dt);
  174. break;
  175. case 'arc':
  176. this.updateArcTrajectory(dt);
  177. break;
  178. }
  179. }
  180. /**
  181. * 更新直线弹道
  182. */
  183. private updateStraightTrajectory(dt: number) {
  184. // 直线弹道保持恒定速度,主要由物理引擎处理
  185. const currentVel = this.rigidBody.linearVelocity;
  186. const targetSpeed = this.config.speed;
  187. // 确保速度保持恒定
  188. const currentSpeed = Math.sqrt(currentVel.x * currentVel.x + currentVel.y * currentVel.y);
  189. if (Math.abs(currentSpeed - targetSpeed) > 1) {
  190. const direction = new Vec2(currentVel.x, currentVel.y).normalize();
  191. this.rigidBody.linearVelocity = direction.multiplyScalar(targetSpeed);
  192. }
  193. }
  194. /**
  195. * 更新抛物线弹道
  196. */
  197. private updateParabolicTrajectory(dt: number) {
  198. // 应用重力影响
  199. const currentVel = this.rigidBody.linearVelocity;
  200. const gravityForce = this.config.gravity * 9.8 * dt;
  201. this.rigidBody.linearVelocity = new Vec2(
  202. currentVel.x,
  203. currentVel.y - gravityForce
  204. );
  205. this.state.currentVelocity.set(currentVel.x, currentVel.y - gravityForce, 0);
  206. }
  207. /**
  208. * 更新追踪弹道
  209. */
  210. private updateHomingTrajectory(dt: number) {
  211. // 追踪延迟后开始追踪
  212. if (this.homingTimer > 0) {
  213. this.homingTimer -= dt;
  214. return;
  215. }
  216. // 确定追踪目标位置(敌人节点 or 返回点)
  217. let targetPos: Vec3 = null;
  218. if (this.state.phase === 'return' && this.state.targetPosition) {
  219. // 回程阶段,使用存储的返回坐标
  220. targetPos = this.state.targetPosition;
  221. } else {
  222. // 主动追踪敌人
  223. if (!this.targetNode || !this.targetNode.isValid) {
  224. this.findTarget();
  225. }
  226. if (this.targetNode && this.targetNode.isValid) {
  227. targetPos = this.targetNode.worldPosition;
  228. }
  229. }
  230. // 若依旧没有目标,直接退出
  231. if (!targetPos) {
  232. return;
  233. }
  234. // 计算追踪力
  235. const currentPos = this.node.worldPosition;
  236. const direction = targetPos.clone().subtract(currentPos).normalize();
  237. // 获取当前速度
  238. const currentVel = this.rigidBody.linearVelocity;
  239. const currentVelVec3 = new Vec3(currentVel.x, currentVel.y, 0);
  240. // 线性插值追踪
  241. const homingForce = this.config.homingStrength * dt * 10;
  242. const targetVelocity = direction.multiplyScalar(this.config.speed);
  243. const newVelocity = currentVelVec3.lerp(targetVelocity, homingForce);
  244. this.rigidBody.linearVelocity = new Vec2(newVelocity.x, newVelocity.y);
  245. this.state.currentVelocity.set(newVelocity);
  246. }
  247. /**
  248. * 更新弧线弹道
  249. */
  250. private updateArcTrajectory(dt: number) {
  251. if (!this.arcDir || !this.arcTargetDir) return;
  252. // === 动态追踪目标 ===
  253. // 若当前没有有效目标,则尝试重新寻找
  254. if (!this.targetNode || !this.targetNode.isValid) {
  255. this.findTarget();
  256. }
  257. // 检查是否到达目标位置(用于西瓜炸弹等爆炸武器)
  258. if (this.state.targetPosition) {
  259. const currentPos = this.node.worldPosition;
  260. const distanceToTarget = Vec3.distance(currentPos, this.state.targetPosition);
  261. // 如果到达目标位置附近(50像素内),触发爆炸
  262. if (distanceToTarget <= 50) {
  263. // 停止运动
  264. if (this.rigidBody) {
  265. this.rigidBody.linearVelocity = new Vec2(0, 0);
  266. }
  267. // 先触发命中效果(包括音效播放)
  268. const hitEffect = this.getComponent('BulletHitEffect') as any;
  269. if (hitEffect && typeof hitEffect.processHit === 'function') {
  270. // 使用当前位置作为命中位置,传入子弹节点作为命中目标
  271. hitEffect.processHit(this.node, currentPos);
  272. }
  273. // 然后通知生命周期组件触发爆炸
  274. const lifecycle = this.getComponent('BulletLifecycle') as any;
  275. if (lifecycle && typeof lifecycle.onHit === 'function') {
  276. lifecycle.onHit(this.node); // 触发爆炸逻辑
  277. }
  278. return;
  279. }
  280. }
  281. // 每帧计算目标方向,使得弹道持续朝向敌人
  282. if (this.targetNode && this.targetNode.isValid) {
  283. const pos = this.node.worldPosition;
  284. const dirToTarget = this.targetNode.worldPosition.clone().subtract(pos).normalize();
  285. this.arcTargetDir.set(dirToTarget);
  286. // 更新目标位置为当前敌人位置
  287. this.state.targetPosition = this.targetNode.worldPosition.clone();
  288. } else if (!this.state.targetPosition) {
  289. // 如果没有目标且没有记录的目标位置,设置一个默认的前方位置
  290. const defaultTarget = this.node.worldPosition.clone().add(this.arcDir.clone().multiplyScalar(200));
  291. this.state.targetPosition = defaultTarget;
  292. }
  293. // 根据与目标距离动态调整转向速率:越近转得越快,避免打圈
  294. let rotateFactor = (this.config.rotateSpeed ?? 0.5) * dt;
  295. if (this.targetNode && this.targetNode.isValid) {
  296. const distance = Vec3.distance(this.node.worldPosition, this.targetNode.worldPosition);
  297. rotateFactor *= (2000 / Math.max(distance, 50));
  298. }
  299. const newDir = new Vec3();
  300. Vec3.slerp(newDir, this.arcDir, this.arcTargetDir, Math.min(1, rotateFactor));
  301. this.arcDir.set(newDir);
  302. // 更新位移 / 速度
  303. if (this.rigidBody) {
  304. this.rigidBody.linearVelocity = new Vec2(this.arcDir.x * this.config.speed, this.arcDir.y * this.config.speed);
  305. } else {
  306. const displacement = this.arcDir.clone().multiplyScalar(this.config.speed * dt);
  307. this.node.worldPosition = this.node.worldPosition.add(displacement);
  308. }
  309. // 更新状态中的当前速度
  310. this.state.currentVelocity.set(this.arcDir.x * this.config.speed, this.arcDir.y * this.config.speed, 0);
  311. }
  312. /**
  313. * 获取当前速度
  314. */
  315. public getCurrentVelocity(): Vec3 {
  316. if (this.config?.type === 'arc') {
  317. return this.arcDir ? this.arcDir.clone().multiplyScalar(this.config.speed) : new Vec3();
  318. }
  319. const vel = this.rigidBody?.linearVelocity;
  320. if (!vel) return new Vec3();
  321. return new Vec3(vel.x, vel.y, 0);
  322. }
  323. /**
  324. * 获取弹道状态
  325. */
  326. public getState(): TrajectoryState {
  327. return this.state;
  328. }
  329. /**
  330. * 设置新的目标位置(用于回旋镖等)
  331. */
  332. public setTargetPosition(target: Vec3) {
  333. this.state.targetPosition = target.clone();
  334. }
  335. /**
  336. * 反转方向(用于回旋镖)
  337. */
  338. public reverseDirection() {
  339. const currentVel = this.rigidBody.linearVelocity;
  340. this.rigidBody.linearVelocity = new Vec2(-currentVel.x, -currentVel.y);
  341. this.state.currentVelocity.multiplyScalar(-1);
  342. this.state.phase = 'return';
  343. }
  344. /**
  345. * 改变方向(用于弹射)
  346. */
  347. public changeDirection(newDirection: Vec3) {
  348. // 归一化新方向
  349. const normalizedDir = newDirection.clone().normalize();
  350. // 保持当前速度大小
  351. const currentSpeed = this.config.speed;
  352. // 更新速度
  353. this.rigidBody.linearVelocity = new Vec2(
  354. normalizedDir.x * currentSpeed,
  355. normalizedDir.y * currentSpeed
  356. );
  357. // 更新状态
  358. this.state.currentVelocity.set(normalizedDir.x * currentSpeed, normalizedDir.y * currentSpeed, 0);
  359. }
  360. /**
  361. * 设置重力
  362. */
  363. public setGravity(gravity: number) {
  364. this.config.gravity = gravity;
  365. }
  366. /**
  367. * 验证配置
  368. */
  369. public static validateConfig(config: BulletTrajectoryConfig): boolean {
  370. if (!config) return false;
  371. if (config.speed <= 0) return false;
  372. if (config.gravity < 0) return false;
  373. if (config.homingStrength < 0 || config.homingStrength > 1) return false;
  374. if (config.homingDelay < 0) return false;
  375. if (config.rotateSpeed !== undefined && (config.rotateSpeed < 0 || config.rotateSpeed > 1)) return false;
  376. return true;
  377. }
  378. }