import { _decorator, Component, Node, Vec2, Vec3, RigidBody2D, find } from 'cc'; const { ccclass, property } = _decorator; /** * 弹道控制器 * 负责控制子弹的运动轨迹 */ export interface BulletTrajectoryConfig { type: 'straight' | 'parabolic' | 'homing' | 'arc'; // 弹道类型 speed: number; // 初始速度 gravity: number; // 重力影响 (arc/straight 可为0) homingStrength: number; // 追踪强度 (0-1) homingDelay: number; // 追踪延迟(秒) /** * 旋转速率 (0~1)。仅在 arc 弹道中使用,值越大转向越快。 */ rotateSpeed?: number; } export interface TrajectoryState { initialVelocity: Vec3; // 初始速度 currentVelocity: Vec3; // 当前速度 startPosition: Vec3; // 起始位置 targetPosition?: Vec3; // 目标位置(追踪用) elapsedTime: number; // 经过时间 phase: 'launch' | 'homing' | 'return'; // 运动阶段 } @ccclass('BulletTrajectory') export class BulletTrajectory extends Component { private config: BulletTrajectoryConfig = null; private state: TrajectoryState = null; private rigidBody: RigidBody2D = null; private targetNode: Node = null; private homingTimer: number = 0; // === Arc Trajectory === private arcDir: Vec3 = null; // 当前方向 private arcTargetDir: Vec3 = null; // 目标方向(最终方向) /** * 初始化弹道 */ public init(config: BulletTrajectoryConfig, direction: Vec3, startPos: Vec3) { this.config = { ...config }; this.rigidBody = this.getComponent(RigidBody2D); if (!this.rigidBody && config.type !== 'arc') { return; } // 初始化状态 this.state = { initialVelocity: direction.clone().multiplyScalar(config.speed), currentVelocity: direction.clone().multiplyScalar(config.speed), startPosition: startPos.clone(), elapsedTime: 0, phase: 'launch' }; this.homingTimer = config.homingDelay; // 设置初始速度 this.applyInitialVelocity(); // 寻找目标(用于追踪弹道) if (config.type === 'homing') { this.findTarget(); } } /** * 设置初始速度 */ private applyInitialVelocity() { switch (this.config.type) { case 'straight': this.rigidBody.linearVelocity = new Vec2( this.state.initialVelocity.x, this.state.initialVelocity.y ); break; case 'parabolic': // 计算抛物线初始速度 const velocity = this.calculateParabolicVelocity(); this.rigidBody.linearVelocity = velocity; this.state.currentVelocity.set(velocity.x, velocity.y, 0); break; case 'homing': this.rigidBody.linearVelocity = new Vec2( this.state.initialVelocity.x, this.state.initialVelocity.y ); break; case 'arc': // 计算带 45° 随机偏移的初始方向 const baseDir = this.state.initialVelocity.clone().normalize(); const sign = Math.random() < 0.5 ? 1 : -1; const rad = 45 * Math.PI / 180 * sign; const cos = Math.cos(rad); const sin = Math.sin(rad); const offsetDir = new Vec3( baseDir.x * cos - baseDir.y * sin, baseDir.x * sin + baseDir.y * cos, 0 ).normalize(); this.arcDir = offsetDir; this.arcTargetDir = baseDir; // 如果有物理组件,则设置线速度;否则后续 updateArcTrajectory 将直接操作位移 if (this.rigidBody) { this.rigidBody.linearVelocity = new Vec2(offsetDir.x * this.config.speed, offsetDir.y * this.config.speed); } // 保存当前速度 this.state.currentVelocity.set(offsetDir.x * this.config.speed, offsetDir.y * this.config.speed, 0); break; } } /** * 计算抛物线初始速度 */ private calculateParabolicVelocity(): Vec2 { // NOTE: // 1. 当目标位于子弹正上/下方时, 原 direction 的 x 分量可能非常小甚至为 0, 导致 vx≈0, 子弹会几乎垂直运动, 看起来像"钢球"直落。 // 2. 对于抛物线弹道, 我们总是希望子弹具备一个最小的水平速度, 并且保证初速度向上( vy>0 ), // 这样才能形成明显的抛物线效果并最终击中目标。 const rawDir = this.state.initialVelocity.clone().normalize(); // 单独提取水平方向, 忽略原始 y 分量, 以保证抛物线始终向前飞行 const horizontalDir = new Vec3(rawDir.x, 0, 0); // 若水平方向过小, 取发射者面朝方向 (rawDir.x 的符号) 作为水平单位向量 if (Math.abs(horizontalDir.x) < 0.01) { horizontalDir.x = rawDir.x >= 0 ? 1 : -1; } horizontalDir.normalize(); const speed = this.config.speed; // 基础水平速度 (保持恒定, 不受重力影响) const vx = horizontalDir.x * speed; // 计算纵向初速度, 使得理论最高点接近 arcHeight // vy = sqrt(2 * g * h) const g = Math.max(0.1, Math.abs(this.config.gravity * 9.8)); // 避免 g=0 导致除0或 vy=0 const desiredHeight = Math.max(1, 20); // 使用固定高度20作为默认抛物线高度 let vy = Math.sqrt(2 * g * desiredHeight); // 如果原始方向有明显的向上分量, 为了兼容旧配置, 适当叠加 if (rawDir.y > 0.1) { vy += rawDir.y * speed * 0.5; // 50% 叠加, 防止过高 } return new Vec2(vx, vy); } /** * 寻找追踪目标 */ private findTarget() { const enemyContainer = find('Canvas/GameLevelUI/enemyContainer'); if (!enemyContainer) return; const enemies = enemyContainer.children.filter(child => child.active && this.isEnemyNode(child) ); if (enemies.length === 0) return; // 寻找最近的敌人 let nearestEnemy: Node = null; let nearestDistance = Infinity; const bulletPos = this.node.worldPosition; for (const enemy of enemies) { const distance = Vec3.distance(bulletPos, enemy.worldPosition); if (distance < nearestDistance) { nearestDistance = distance; nearestEnemy = enemy; } } if (nearestEnemy) { this.targetNode = nearestEnemy; this.state.targetPosition = nearestEnemy.worldPosition.clone(); } } /** * 判断是否为敌人节点 */ private isEnemyNode(node: Node): boolean { const name = node.name.toLowerCase(); return name.includes('enemy') || name.includes('敌人') || node.getComponent('EnemyInstance') !== null; } update(dt: number) { if (!this.config || !this.state) return; this.state.elapsedTime += dt; switch (this.config.type) { case 'straight': this.updateStraightTrajectory(dt); break; case 'parabolic': this.updateParabolicTrajectory(dt); break; case 'homing': this.updateHomingTrajectory(dt); break; case 'arc': this.updateArcTrajectory(dt); break; } } /** * 更新直线弹道 */ private updateStraightTrajectory(dt: number) { // 直线弹道保持恒定速度,主要由物理引擎处理 const currentVel = this.rigidBody.linearVelocity; const targetSpeed = this.config.speed; // 确保速度保持恒定 const currentSpeed = Math.sqrt(currentVel.x * currentVel.x + currentVel.y * currentVel.y); if (Math.abs(currentSpeed - targetSpeed) > 1) { const direction = new Vec2(currentVel.x, currentVel.y).normalize(); this.rigidBody.linearVelocity = direction.multiplyScalar(targetSpeed); } } /** * 更新抛物线弹道 */ private updateParabolicTrajectory(dt: number) { // 应用重力影响 const currentVel = this.rigidBody.linearVelocity; const gravityForce = this.config.gravity * 9.8 * dt; this.rigidBody.linearVelocity = new Vec2( currentVel.x, currentVel.y - gravityForce ); this.state.currentVelocity.set(currentVel.x, currentVel.y - gravityForce, 0); } /** * 更新追踪弹道 */ private updateHomingTrajectory(dt: number) { // 追踪延迟后开始追踪 if (this.homingTimer > 0) { this.homingTimer -= dt; return; } // 确定追踪目标位置(敌人节点 or 返回点) let targetPos: Vec3 = null; if (this.state.phase === 'return' && this.state.targetPosition) { // 回程阶段,使用存储的返回坐标 targetPos = this.state.targetPosition; } else { // 主动追踪敌人 if (!this.targetNode || !this.targetNode.isValid) { this.findTarget(); } if (this.targetNode && this.targetNode.isValid) { targetPos = this.targetNode.worldPosition; } } // 若依旧没有目标,直接退出 if (!targetPos) { return; } // 计算追踪力 const currentPos = this.node.worldPosition; const direction = targetPos.clone().subtract(currentPos).normalize(); // 获取当前速度 const currentVel = this.rigidBody.linearVelocity; const currentVelVec3 = new Vec3(currentVel.x, currentVel.y, 0); // 线性插值追踪 const homingForce = this.config.homingStrength * dt * 10; const targetVelocity = direction.multiplyScalar(this.config.speed); const newVelocity = currentVelVec3.lerp(targetVelocity, homingForce); this.rigidBody.linearVelocity = new Vec2(newVelocity.x, newVelocity.y); this.state.currentVelocity.set(newVelocity); } /** * 更新弧线弹道 */ private updateArcTrajectory(dt: number) { if (!this.arcDir || !this.arcTargetDir) return; // === 动态追踪目标 === // 若当前没有有效目标,则尝试重新寻找 if (!this.targetNode || !this.targetNode.isValid) { this.findTarget(); } // 每帧计算目标方向,使得弹道持续朝向敌人 if (this.targetNode && this.targetNode.isValid) { const pos = this.node.worldPosition; const dirToTarget = this.targetNode.worldPosition.clone().subtract(pos).normalize(); this.arcTargetDir.set(dirToTarget); } // 根据与目标距离动态调整转向速率:越近转得越快,避免打圈 let rotateFactor = (this.config.rotateSpeed ?? 0.5) * dt; if (this.targetNode && this.targetNode.isValid) { const distance = Vec3.distance(this.node.worldPosition, this.targetNode.worldPosition); rotateFactor *= (2000 / Math.max(distance, 50)); } const newDir = new Vec3(); Vec3.slerp(newDir, this.arcDir, this.arcTargetDir, Math.min(1, rotateFactor)); this.arcDir.set(newDir); // 更新位移 / 速度 if (this.rigidBody) { this.rigidBody.linearVelocity = new Vec2(this.arcDir.x * this.config.speed, this.arcDir.y * this.config.speed); } else { const displacement = this.arcDir.clone().multiplyScalar(this.config.speed * dt); this.node.worldPosition = this.node.worldPosition.add(displacement); } // 更新状态中的当前速度 this.state.currentVelocity.set(this.arcDir.x * this.config.speed, this.arcDir.y * this.config.speed, 0); } /** * 获取当前速度 */ public getCurrentVelocity(): Vec3 { if (this.config?.type === 'arc') { return this.arcDir ? this.arcDir.clone().multiplyScalar(this.config.speed) : new Vec3(); } const vel = this.rigidBody?.linearVelocity; if (!vel) return new Vec3(); return new Vec3(vel.x, vel.y, 0); } /** * 获取弹道状态 */ public getState(): TrajectoryState { return this.state; } /** * 设置新的目标位置(用于回旋镖等) */ public setTargetPosition(target: Vec3) { this.state.targetPosition = target.clone(); } /** * 反转方向(用于回旋镖) */ public reverseDirection() { const currentVel = this.rigidBody.linearVelocity; this.rigidBody.linearVelocity = new Vec2(-currentVel.x, -currentVel.y); this.state.currentVelocity.multiplyScalar(-1); this.state.phase = 'return'; } /** * 改变方向(用于弹射) */ public changeDirection(newDirection: Vec3) { // 归一化新方向 const normalizedDir = newDirection.clone().normalize(); // 保持当前速度大小 const currentSpeed = this.config.speed; // 更新速度 this.rigidBody.linearVelocity = new Vec2( normalizedDir.x * currentSpeed, normalizedDir.y * currentSpeed ); // 更新状态 this.state.currentVelocity.set(normalizedDir.x * currentSpeed, normalizedDir.y * currentSpeed, 0); } /** * 设置重力 */ public setGravity(gravity: number) { this.config.gravity = gravity; } /** * 验证配置 */ public static validateConfig(config: BulletTrajectoryConfig): boolean { if (!config) return false; if (config.speed <= 0) return false; if (config.gravity < 0) return false; if (config.homingStrength < 0 || config.homingStrength > 1) return false; if (config.homingDelay < 0) return false; if (config.rotateSpeed !== undefined && (config.rotateSpeed < 0 || config.rotateSpeed > 1)) return false; return true; } }