import { _decorator, Component, Node, Vec2, Vec3, RigidBody2D, find } from 'cc'; const { ccclass, property } = _decorator; /** * 弹道控制器 * 负责控制子弹的运动轨迹 */ export interface BulletTrajectoryConfig { type: 'straight' | 'parabolic' | 'homing'; // 弹道类型 speed: number; // 初始速度 gravity: number; // 重力影响 homingStrength: number; // 追踪强度 (0-1) homingDelay: 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; /** * 初始化弹道 */ public init(config: BulletTrajectoryConfig, direction: Vec3, startPos: Vec3) { this.config = { ...config }; this.rigidBody = this.getComponent(RigidBody2D); if (!this.rigidBody) { console.error('BulletTrajectory: 需要RigidBody2D组件'); 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(); } console.log(`🎯 弹道初始化: ${config.type}, 速度: ${config.speed}`); } /** * 设置初始速度 */ 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; } } /** * 计算抛物线初始速度 */ 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(); console.log(`🎯 弹道锁定目标: ${nearestEnemy.name}`); } } /** * 判断是否为敌人节点 */ 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 || !this.rigidBody) 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; } } /** * 更新直线弹道 */ 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); } /** * 获取当前速度 */ public getCurrentVelocity(): Vec3 { const vel = this.rigidBody.linearVelocity; 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'; console.log('🔄 弹道反转方向'); } /** * 改变方向(用于弹射) */ 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); console.log('🎾 弹道方向已改变:', normalizedDir); } /** * 设置重力 */ 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; return true; } }