BulletTrajectory.ts 15 KB

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