BulletTrajectory.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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' | 'arc' | 'homing_arc'; // 弹道类型
  9. speed: number; // 初始速度
  10. gravity: number; // 重力影响
  11. arcHeight: number; // 弧线高度
  12. homingStrength: number; // 追踪强度 (0-1)
  13. homingDelay: number; // 追踪延迟(秒)
  14. }
  15. export interface TrajectoryState {
  16. initialVelocity: Vec3; // 初始速度
  17. currentVelocity: Vec3; // 当前速度
  18. startPosition: Vec3; // 起始位置
  19. targetPosition?: Vec3; // 目标位置(追踪用)
  20. elapsedTime: number; // 经过时间
  21. phase: 'launch' | 'homing' | 'return'; // 运动阶段
  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. /**
  31. * 初始化弹道
  32. */
  33. public init(config: BulletTrajectoryConfig, direction: Vec3, startPos: Vec3) {
  34. this.config = { ...config };
  35. this.rigidBody = this.getComponent(RigidBody2D);
  36. if (!this.rigidBody) {
  37. console.error('BulletTrajectory: 需要RigidBody2D组件');
  38. return;
  39. }
  40. // 初始化状态
  41. this.state = {
  42. initialVelocity: direction.clone().multiplyScalar(config.speed),
  43. currentVelocity: direction.clone().multiplyScalar(config.speed),
  44. startPosition: startPos.clone(),
  45. elapsedTime: 0,
  46. phase: 'launch'
  47. };
  48. this.homingTimer = config.homingDelay;
  49. // 设置初始速度
  50. this.applyInitialVelocity();
  51. // 寻找目标(用于追踪弹道)
  52. if (config.type === 'homing_arc') {
  53. this.findTarget();
  54. }
  55. console.log(`🎯 弹道初始化: ${config.type}, 速度: ${config.speed}`);
  56. }
  57. /**
  58. * 设置初始速度
  59. */
  60. private applyInitialVelocity() {
  61. switch (this.config.type) {
  62. case 'straight':
  63. this.rigidBody.linearVelocity = new Vec2(
  64. this.state.initialVelocity.x,
  65. this.state.initialVelocity.y
  66. );
  67. break;
  68. case 'parabolic':
  69. case 'arc':
  70. case 'homing_arc':
  71. // 计算抛物线初始速度
  72. const velocity = this.calculateParabolicVelocity();
  73. this.rigidBody.linearVelocity = velocity;
  74. this.state.currentVelocity.set(velocity.x, velocity.y, 0);
  75. break;
  76. }
  77. }
  78. /**
  79. * 计算抛物线初始速度
  80. */
  81. private calculateParabolicVelocity(): Vec2 {
  82. // NOTE:
  83. // 1. 当目标位于子弹正上/下方时, 原 direction 的 x 分量可能非常小甚至为 0, 导致 vx≈0, 子弹会几乎垂直运动, 看起来像"钢球"直落。
  84. // 2. 对于抛物线/弧线弹道, 我们总是希望子弹具备一个最小的水平速度, 并且保证初速度向上( vy>0 ),
  85. // 这样才能形成明显的抛物或弧线效果并最终击中目标。
  86. const rawDir = this.state.initialVelocity.clone().normalize();
  87. // 单独提取水平方向, 忽略原始 y 分量, 以保证抛物线始终向前飞行
  88. const horizontalDir = new Vec3(rawDir.x, 0, 0);
  89. // 若水平方向过小, 取发射者面朝方向 (rawDir.x 的符号) 作为水平单位向量
  90. if (Math.abs(horizontalDir.x) < 0.01) {
  91. horizontalDir.x = rawDir.x >= 0 ? 1 : -1;
  92. }
  93. horizontalDir.normalize();
  94. const speed = this.config.speed;
  95. // 基础水平速度 (保持恒定, 不受重力影响)
  96. const vx = horizontalDir.x * speed;
  97. // 计算纵向初速度, 使得理论最高点接近 arcHeight
  98. // vy = sqrt(2 * g * h)
  99. const g = Math.max(0.1, Math.abs(this.config.gravity * 9.8)); // 避免 g=0 导致除0或 vy=0
  100. const desiredHeight = Math.max(1, this.config.arcHeight); // 至少 1 避免 0 导致 vy=0
  101. let vy = Math.sqrt(2 * g * desiredHeight);
  102. // 如果原始方向有明显的向上分量, 为了兼容旧配置, 适当叠加
  103. if (rawDir.y > 0.1) {
  104. vy += rawDir.y * speed * 0.5; // 50% 叠加, 防止过高
  105. }
  106. return new Vec2(vx, vy);
  107. }
  108. /**
  109. * 寻找追踪目标
  110. */
  111. private findTarget() {
  112. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  113. if (!enemyContainer) return;
  114. const enemies = enemyContainer.children.filter(child =>
  115. child.active && this.isEnemyNode(child)
  116. );
  117. if (enemies.length === 0) return;
  118. // 寻找最近的敌人
  119. let nearestEnemy: Node = null;
  120. let nearestDistance = Infinity;
  121. const bulletPos = this.node.worldPosition;
  122. for (const enemy of enemies) {
  123. const distance = Vec3.distance(bulletPos, enemy.worldPosition);
  124. if (distance < nearestDistance) {
  125. nearestDistance = distance;
  126. nearestEnemy = enemy;
  127. }
  128. }
  129. if (nearestEnemy) {
  130. this.targetNode = nearestEnemy;
  131. this.state.targetPosition = nearestEnemy.worldPosition.clone();
  132. console.log(`🎯 弹道锁定目标: ${nearestEnemy.name}`);
  133. }
  134. }
  135. /**
  136. * 判断是否为敌人节点
  137. */
  138. private isEnemyNode(node: Node): boolean {
  139. const name = node.name.toLowerCase();
  140. return name.includes('enemy') ||
  141. name.includes('敌人') ||
  142. node.getComponent('EnemyInstance') !== null;
  143. }
  144. update(dt: number) {
  145. if (!this.config || !this.state || !this.rigidBody) return;
  146. this.state.elapsedTime += dt;
  147. switch (this.config.type) {
  148. case 'straight':
  149. this.updateStraightTrajectory(dt);
  150. break;
  151. case 'parabolic':
  152. this.updateParabolicTrajectory(dt);
  153. break;
  154. case 'arc':
  155. this.updateArcTrajectory(dt);
  156. break;
  157. case 'homing_arc':
  158. this.updateHomingTrajectory(dt);
  159. break;
  160. }
  161. }
  162. /**
  163. * 更新直线弹道
  164. */
  165. private updateStraightTrajectory(dt: number) {
  166. // 直线弹道保持恒定速度,主要由物理引擎处理
  167. const currentVel = this.rigidBody.linearVelocity;
  168. const targetSpeed = this.config.speed;
  169. // 确保速度保持恒定
  170. const currentSpeed = Math.sqrt(currentVel.x * currentVel.x + currentVel.y * currentVel.y);
  171. if (Math.abs(currentSpeed - targetSpeed) > 1) {
  172. const direction = new Vec2(currentVel.x, currentVel.y).normalize();
  173. this.rigidBody.linearVelocity = direction.multiplyScalar(targetSpeed);
  174. }
  175. }
  176. /**
  177. * 更新抛物线弹道
  178. */
  179. private updateParabolicTrajectory(dt: number) {
  180. // 应用重力影响
  181. const currentVel = this.rigidBody.linearVelocity;
  182. const gravityForce = this.config.gravity * 9.8 * dt;
  183. this.rigidBody.linearVelocity = new Vec2(
  184. currentVel.x,
  185. currentVel.y - gravityForce
  186. );
  187. this.state.currentVelocity.set(currentVel.x, currentVel.y - gravityForce, 0);
  188. }
  189. /**
  190. * 更新弧线弹道
  191. */
  192. private updateArcTrajectory(dt: number) {
  193. // 先应用基础的抛物线逻辑 (受重力影响)
  194. this.updateParabolicTrajectory(dt);
  195. // 再在垂直方向叠加一个小幅度的正弦扰动, 让轨迹更加圆润。
  196. const t = this.state.elapsedTime;
  197. const sinus = Math.sin(t * Math.PI); // [-1,1]
  198. const extraVy = sinus * this.config.arcHeight * 0.05; // 0.05 系数保证不至于过大
  199. const curVel = this.rigidBody.linearVelocity;
  200. this.rigidBody.linearVelocity = new Vec2(curVel.x, curVel.y + extraVy);
  201. }
  202. /**
  203. * 更新追踪弹道
  204. */
  205. private updateHomingTrajectory(dt: number) {
  206. // 先按抛物线运动
  207. this.updateParabolicTrajectory(dt);
  208. // 追踪延迟后开始追踪
  209. if (this.homingTimer > 0) {
  210. this.homingTimer -= dt;
  211. return;
  212. }
  213. // 确定追踪目标位置(敌人节点 or 返回点)
  214. let targetPos: Vec3 = null;
  215. if (this.state.phase === 'return' && this.state.targetPosition) {
  216. // 回程阶段,使用存储的返回坐标
  217. targetPos = this.state.targetPosition;
  218. } else {
  219. // 主动追踪敌人
  220. if (!this.targetNode || !this.targetNode.isValid) {
  221. this.findTarget();
  222. }
  223. if (this.targetNode && this.targetNode.isValid) {
  224. targetPos = this.targetNode.worldPosition;
  225. }
  226. }
  227. // 若依旧没有目标,直接退出
  228. if (!targetPos) {
  229. return;
  230. }
  231. // 计算追踪力
  232. const currentPos = this.node.worldPosition;
  233. const direction = targetPos.clone().subtract(currentPos).normalize();
  234. // 获取当前速度
  235. const currentVel = this.rigidBody.linearVelocity;
  236. const currentVelVec3 = new Vec3(currentVel.x, currentVel.y, 0);
  237. // 线性插值追踪
  238. const homingForce = this.config.homingStrength * dt * 10;
  239. const targetVelocity = direction.multiplyScalar(this.config.speed);
  240. const newVelocity = currentVelVec3.lerp(targetVelocity, homingForce);
  241. this.rigidBody.linearVelocity = new Vec2(newVelocity.x, newVelocity.y);
  242. this.state.currentVelocity.set(newVelocity);
  243. }
  244. /**
  245. * 获取当前速度
  246. */
  247. public getCurrentVelocity(): Vec3 {
  248. const vel = this.rigidBody.linearVelocity;
  249. return new Vec3(vel.x, vel.y, 0);
  250. }
  251. /**
  252. * 获取弹道状态
  253. */
  254. public getState(): TrajectoryState {
  255. return this.state;
  256. }
  257. /**
  258. * 设置新的目标位置(用于回旋镖等)
  259. */
  260. public setTargetPosition(target: Vec3) {
  261. this.state.targetPosition = target.clone();
  262. }
  263. /**
  264. * 反转方向(用于回旋镖)
  265. */
  266. public reverseDirection() {
  267. const currentVel = this.rigidBody.linearVelocity;
  268. this.rigidBody.linearVelocity = new Vec2(-currentVel.x, -currentVel.y);
  269. this.state.currentVelocity.multiplyScalar(-1);
  270. this.state.phase = 'return';
  271. console.log('🔄 弹道反转方向');
  272. }
  273. /**
  274. * 改变方向(用于弹射)
  275. */
  276. public changeDirection(newDirection: Vec3) {
  277. // 归一化新方向
  278. const normalizedDir = newDirection.clone().normalize();
  279. // 保持当前速度大小
  280. const currentSpeed = this.config.speed;
  281. // 更新速度
  282. this.rigidBody.linearVelocity = new Vec2(
  283. normalizedDir.x * currentSpeed,
  284. normalizedDir.y * currentSpeed
  285. );
  286. // 更新状态
  287. this.state.currentVelocity.set(normalizedDir.x * currentSpeed, normalizedDir.y * currentSpeed, 0);
  288. console.log('🎾 弹道方向已改变:', normalizedDir);
  289. }
  290. /**
  291. * 设置重力
  292. */
  293. public setGravity(gravity: number) {
  294. this.config.gravity = gravity;
  295. }
  296. /**
  297. * 验证配置
  298. */
  299. public static validateConfig(config: BulletTrajectoryConfig): boolean {
  300. if (!config) return false;
  301. if (config.speed <= 0) return false;
  302. if (config.gravity < 0) return false;
  303. if (config.arcHeight < 0) return false;
  304. if (config.homingStrength < 0 || config.homingStrength > 1) return false;
  305. if (config.homingDelay < 0) return false;
  306. return true;
  307. }
  308. }