BulletTrajectory.ts 11 KB

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