BulletTrajectory.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. const direction = this.state.initialVelocity.clone().normalize();
  83. const speed = this.config.speed;
  84. // 基础抛物线速度
  85. let vx = direction.x * speed;
  86. let vy = direction.y * speed;
  87. // 如果有弧线高度,调整y轴速度
  88. if (this.config.arcHeight > 0) {
  89. // 计算到达弧线顶点需要的额外速度
  90. const timeToApex = Math.abs(vx) / speed; // 简化计算
  91. const extraVy = Math.sqrt(2 * Math.abs(this.config.gravity * 9.8) * this.config.arcHeight);
  92. vy += extraVy;
  93. }
  94. return new Vec2(vx, vy);
  95. }
  96. /**
  97. * 寻找追踪目标
  98. */
  99. private findTarget() {
  100. const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
  101. if (!enemyContainer) return;
  102. const enemies = enemyContainer.children.filter(child =>
  103. child.active && this.isEnemyNode(child)
  104. );
  105. if (enemies.length === 0) return;
  106. // 寻找最近的敌人
  107. let nearestEnemy: Node = null;
  108. let nearestDistance = Infinity;
  109. const bulletPos = this.node.worldPosition;
  110. for (const enemy of enemies) {
  111. const distance = Vec3.distance(bulletPos, enemy.worldPosition);
  112. if (distance < nearestDistance) {
  113. nearestDistance = distance;
  114. nearestEnemy = enemy;
  115. }
  116. }
  117. if (nearestEnemy) {
  118. this.targetNode = nearestEnemy;
  119. this.state.targetPosition = nearestEnemy.worldPosition.clone();
  120. console.log(`🎯 弹道锁定目标: ${nearestEnemy.name}`);
  121. }
  122. }
  123. /**
  124. * 判断是否为敌人节点
  125. */
  126. private isEnemyNode(node: Node): boolean {
  127. const name = node.name.toLowerCase();
  128. return name.includes('enemy') ||
  129. name.includes('敌人') ||
  130. node.getComponent('EnemyInstance') !== null;
  131. }
  132. update(dt: number) {
  133. if (!this.config || !this.state || !this.rigidBody) return;
  134. this.state.elapsedTime += dt;
  135. switch (this.config.type) {
  136. case 'straight':
  137. this.updateStraightTrajectory(dt);
  138. break;
  139. case 'parabolic':
  140. this.updateParabolicTrajectory(dt);
  141. break;
  142. case 'arc':
  143. this.updateArcTrajectory(dt);
  144. break;
  145. case 'homing_arc':
  146. this.updateHomingTrajectory(dt);
  147. break;
  148. }
  149. }
  150. /**
  151. * 更新直线弹道
  152. */
  153. private updateStraightTrajectory(dt: number) {
  154. // 直线弹道保持恒定速度,主要由物理引擎处理
  155. const currentVel = this.rigidBody.linearVelocity;
  156. const targetSpeed = this.config.speed;
  157. // 确保速度保持恒定
  158. const currentSpeed = Math.sqrt(currentVel.x * currentVel.x + currentVel.y * currentVel.y);
  159. if (Math.abs(currentSpeed - targetSpeed) > 1) {
  160. const direction = new Vec2(currentVel.x, currentVel.y).normalize();
  161. this.rigidBody.linearVelocity = direction.multiplyScalar(targetSpeed);
  162. }
  163. }
  164. /**
  165. * 更新抛物线弹道
  166. */
  167. private updateParabolicTrajectory(dt: number) {
  168. // 应用重力影响
  169. const currentVel = this.rigidBody.linearVelocity;
  170. const gravityForce = this.config.gravity * 9.8 * dt;
  171. this.rigidBody.linearVelocity = new Vec2(
  172. currentVel.x,
  173. currentVel.y - gravityForce
  174. );
  175. this.state.currentVelocity.set(currentVel.x, currentVel.y - gravityForce, 0);
  176. }
  177. /**
  178. * 更新弧线弹道
  179. */
  180. private updateArcTrajectory(dt: number) {
  181. // 弧线弹道结合了直线和抛物线特性
  182. const t = this.state.elapsedTime;
  183. const arcPeriod = 2.0; // 弧线周期
  184. const arcFactor = Math.sin(t * Math.PI / arcPeriod) * this.config.arcHeight * 0.1;
  185. const currentVel = this.rigidBody.linearVelocity;
  186. this.rigidBody.linearVelocity = new Vec2(
  187. currentVel.x,
  188. currentVel.y + arcFactor * dt
  189. );
  190. }
  191. /**
  192. * 更新追踪弹道
  193. */
  194. private updateHomingTrajectory(dt: number) {
  195. // 先按抛物线运动
  196. this.updateParabolicTrajectory(dt);
  197. // 追踪延迟后开始追踪
  198. if (this.homingTimer > 0) {
  199. this.homingTimer -= dt;
  200. return;
  201. }
  202. if (!this.targetNode || !this.targetNode.isValid) {
  203. this.findTarget(); // 重新寻找目标
  204. return;
  205. }
  206. // 计算追踪力
  207. const currentPos = this.node.worldPosition;
  208. const targetPos = this.targetNode.worldPosition;
  209. const direction = targetPos.clone().subtract(currentPos).normalize();
  210. // 获取当前速度
  211. const currentVel = this.rigidBody.linearVelocity;
  212. const currentVelVec3 = new Vec3(currentVel.x, currentVel.y, 0);
  213. // 线性插值追踪
  214. const homingForce = this.config.homingStrength * dt * 10;
  215. const targetVelocity = direction.multiplyScalar(this.config.speed);
  216. const newVelocity = currentVelVec3.lerp(targetVelocity, homingForce);
  217. this.rigidBody.linearVelocity = new Vec2(newVelocity.x, newVelocity.y);
  218. this.state.currentVelocity.set(newVelocity);
  219. }
  220. /**
  221. * 获取当前速度
  222. */
  223. public getCurrentVelocity(): Vec3 {
  224. const vel = this.rigidBody.linearVelocity;
  225. return new Vec3(vel.x, vel.y, 0);
  226. }
  227. /**
  228. * 获取弹道状态
  229. */
  230. public getState(): TrajectoryState {
  231. return this.state;
  232. }
  233. /**
  234. * 设置新的目标位置(用于回旋镖等)
  235. */
  236. public setTargetPosition(target: Vec3) {
  237. this.state.targetPosition = target.clone();
  238. }
  239. /**
  240. * 反转方向(用于回旋镖)
  241. */
  242. public reverseDirection() {
  243. const currentVel = this.rigidBody.linearVelocity;
  244. this.rigidBody.linearVelocity = new Vec2(-currentVel.x, -currentVel.y);
  245. this.state.currentVelocity.multiplyScalar(-1);
  246. this.state.phase = 'return';
  247. console.log('🔄 弹道反转方向');
  248. }
  249. /**
  250. * 改变方向(用于弹射)
  251. */
  252. public changeDirection(newDirection: Vec3) {
  253. // 归一化新方向
  254. const normalizedDir = newDirection.clone().normalize();
  255. // 保持当前速度大小
  256. const currentSpeed = this.config.speed;
  257. // 更新速度
  258. this.rigidBody.linearVelocity = new Vec2(
  259. normalizedDir.x * currentSpeed,
  260. normalizedDir.y * currentSpeed
  261. );
  262. // 更新状态
  263. this.state.currentVelocity.set(normalizedDir.x * currentSpeed, normalizedDir.y * currentSpeed, 0);
  264. console.log('🎾 弹道方向已改变:', normalizedDir);
  265. }
  266. /**
  267. * 设置重力
  268. */
  269. public setGravity(gravity: number) {
  270. this.config.gravity = gravity;
  271. }
  272. /**
  273. * 验证配置
  274. */
  275. public static validateConfig(config: BulletTrajectoryConfig): boolean {
  276. if (!config) return false;
  277. if (config.speed <= 0) return false;
  278. if (config.gravity < 0) return false;
  279. if (config.arcHeight < 0) return false;
  280. if (config.homingStrength < 0 || config.homingStrength > 1) return false;
  281. if (config.homingDelay < 0) return false;
  282. return true;
  283. }
  284. }