BulletTrajectory.ts 15 KB

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