import { _decorator, Component, Node, Vec2, Vec3, RigidBody2D, find } from 'cc'; import { BulletTrajectoryConfig } from '../../Core/ConfigManager'; const { ccclass, property } = _decorator; /** * 弹道控制器 * 负责控制子弹的运动轨迹 */ export interface TrajectoryState { initialVelocity: Vec3; // 初始速度 currentVelocity: Vec3; // 当前速度 startPosition: Vec3; // 起始位置 targetPosition?: Vec3; // 目标位置(追踪用) elapsedTime: number; // 经过时间 phase: 'launch' | 'homing' | 'return'; // 运动阶段 // 路径记录相关 flightPath: Vec3[]; // 飞行路径记录 pathRecordInterval: number; // 路径记录间隔(毫秒) lastRecordTime: number; // 上次记录时间 returnPathIndex: number; // 返回路径索引 // 发射源方块节点 sourceBlock?: Node; // 发射源方块节点(用于动态获取返回位置) } @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, sourceBlock?: Node) { 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', // 路径记录初始化 flightPath: [startPos.clone()], pathRecordInterval: 50, // 每50毫秒记录一次位置 lastRecordTime: 0, returnPathIndex: -1, // 存储发射源方块节点 sourceBlock: sourceBlock }; 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 { // 检查是否为EnemySprite子节点 if (node.name === 'EnemySprite' && node.parent) { return node.parent.getComponent('EnemyInstance') !== null; } // 兼容旧的敌人检测逻辑 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; // 记录路径(仅对回旋镖) this.recordFlightPath(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(); } // 检查是否到达目标位置(爆炸武器和回旋镖都适用,但处理方式不同) const lifecycle = this.getComponent('BulletLifecycle') as any; const isBoomerang = lifecycle && lifecycle.getState && lifecycle.getState().phase !== undefined; if (this.state.targetPosition) { const currentPos = this.node.worldPosition; const distanceToTarget = Vec3.distance(currentPos, this.state.targetPosition); // 如果到达目标位置附近(50像素内) if (distanceToTarget <= 50) { if (isBoomerang) { // 回旋镖:触发命中效果但不爆炸,开始返回 const hitEffect = this.getComponent('BulletHitEffect') as any; if (hitEffect && typeof hitEffect.processHit === 'function') { // 对目标位置附近的敌人造成伤害 const enemyContainer = find('Canvas/GameLevelUI/enemyContainer'); if (enemyContainer) { const enemies = enemyContainer.children.filter(child => child.active && this.isEnemyNode(child) ); // 寻找目标位置附近的敌人 for (const enemy of enemies) { const distanceToEnemy = Vec3.distance(currentPos, enemy.worldPosition); if (distanceToEnemy <= 50) { hitEffect.processHit(enemy, currentPos); break; // 只命中一个敌人 } } } } // 通知生命周期组件处理命中(回旋镖会开始返回而不是销毁) if (lifecycle && typeof lifecycle.onHit === 'function') { lifecycle.onHit(this.targetNode || this.node); } } else { // 爆炸武器:停止运动并触发爆炸 if (this.rigidBody) { this.rigidBody.linearVelocity = new Vec2(0, 0); } // 先触发命中效果(包括音效播放) const hitEffect = this.getComponent('BulletHitEffect') as any; if (hitEffect && typeof hitEffect.processHit === 'function') { // 使用当前位置作为命中位置,传入子弹节点作为命中目标 hitEffect.processHit(this.node, currentPos); } // 然后通知生命周期组件触发爆炸 if (lifecycle && typeof lifecycle.onHit === 'function') { lifecycle.onHit(this.node); // 触发爆炸逻辑 } return; } } } // 根据回旋镖状态决定目标方向 if (isBoomerang && lifecycle.getState().phase === 'returning') { // 返回阶段:直接朝向目标位置(方块当前位置) if (this.state.targetPosition) { const pos = this.node.worldPosition; const dirToTarget = this.state.targetPosition.clone().subtract(pos).normalize(); this.arcTargetDir.set(dirToTarget); // 检查是否到达目标位置 const distanceToTarget = Vec3.distance(pos, this.state.targetPosition); if (distanceToTarget <= 30) { // 到达目标,销毁子弹 if (lifecycle && typeof lifecycle.forceDestroy === 'function') { lifecycle.forceDestroy(); } return; } } } else { // 主动追踪阶段:朝向敌人 if (this.targetNode && this.targetNode.isValid) { const pos = this.node.worldPosition; const dirToTarget = this.targetNode.worldPosition.clone().subtract(pos).normalize(); this.arcTargetDir.set(dirToTarget); // 对于回旋镖,检查是否足够接近敌人来触发命中 if (isBoomerang) { const distanceToEnemy = Vec3.distance(pos, this.targetNode.worldPosition); if (distanceToEnemy <= 30) { // 30像素内算命中 // 触发命中效果 const hitEffect = this.getComponent('BulletHitEffect') as any; if (hitEffect && typeof hitEffect.processHit === 'function') { hitEffect.processHit(this.targetNode, pos); } // 通知生命周期组件处理命中 if (lifecycle && typeof lifecycle.onHit === 'function') { lifecycle.onHit(this.targetNode); } } } // 更新目标位置为当前敌人位置 this.state.targetPosition = this.targetNode.worldPosition.clone(); } else if (!this.state.targetPosition) { // 如果没有目标且没有记录的目标位置,设置一个默认的前方位置 const defaultTarget = this.node.worldPosition.clone().add(this.arcDir.clone().multiplyScalar(200)); this.state.targetPosition = defaultTarget; } } // 根据与目标距离动态调整转向速率:越近转得越快,避免打圈 let rotateFactor = (this.config.rotateSpeed ?? 0.5) * dt; if (isBoomerang && lifecycle.getState().phase === 'returning') { // 回旋镖返回阶段:根据距离调整转向速率,确保平滑返回 if (this.state.targetPosition) { const distanceToTarget = Vec3.distance(this.node.worldPosition, this.state.targetPosition); // 根据距离动态调整转向速率,距离越近转向越快 if (distanceToTarget < 50) { rotateFactor *= 4.0; // 非常接近目标点时快速转向 } else if (distanceToTarget < 100) { rotateFactor *= 2.5; // 接近目标点时加快转向 } else if (distanceToTarget < 200) { rotateFactor *= 1.8; // 中等距离时适度加快转向 } else { rotateFactor *= 1.2; // 远距离时使用基础转向速率 } } } else 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; } /** * 记录飞行路径(仅对回旋镖) */ private recordFlightPath(dt: number) { // 检查是否为回旋镖 const lifecycle = this.getComponent('BulletLifecycle') as any; const isBoomerang = lifecycle && lifecycle.getState && lifecycle.getState().phase !== undefined; if (!isBoomerang) return; // 只在非返回阶段记录路径 if (lifecycle.getState().phase === 'returning') return; // 检查是否到了记录时间 this.state.lastRecordTime += dt * 1000; // 转换为毫秒 if (this.state.lastRecordTime >= this.state.pathRecordInterval) { const currentPos = this.node.worldPosition.clone(); // 避免记录重复位置 const lastPos = this.state.flightPath[this.state.flightPath.length - 1]; const distance = Vec3.distance(currentPos, lastPos); if (distance > 10) { // 只有移动距离超过10像素才记录 this.state.flightPath.push(currentPos); this.state.lastRecordTime = 0; } } } /** * 获取返回路径中的下一个目标点 */ private getNextReturnTarget(): Vec3 | null { if (this.state.flightPath.length === 0) return null; // 如果还没有开始返回路径,初始化索引 if (this.state.returnPathIndex === -1) { this.state.returnPathIndex = this.state.flightPath.length - 1; } // 检查当前位置是否接近目标点 if (this.state.returnPathIndex >= 0) { const targetPos = this.state.flightPath[this.state.returnPathIndex]; const currentPos = this.node.worldPosition; const distance = Vec3.distance(currentPos, targetPos); // 动态调整接近距离:路径点越少,接近距离越大,避免过于严格的路径跟随 const approachDistance = Math.max(25, Math.min(50, 200 / this.state.flightPath.length)); // 如果接近当前目标点,移动到下一个点 if (distance <= approachDistance) { this.state.returnPathIndex--; } // 返回当前目标点,如果有多个路径点则进行平滑插值 if (this.state.returnPathIndex >= 0) { const currentTarget = this.state.flightPath[this.state.returnPathIndex]; // 如果还有下一个路径点,进行平滑插值 if (this.state.returnPathIndex > 0) { const nextTarget = this.state.flightPath[this.state.returnPathIndex - 1]; const progress = Math.min(1, (approachDistance - distance) / approachDistance); if (progress > 0) { // 在当前目标点和下一个目标点之间进行插值 const smoothTarget = new Vec3(); Vec3.lerp(smoothTarget, currentTarget, nextTarget, progress * 0.3); return smoothTarget; } } return currentTarget; } } // 如果已经遍历完所有路径点,返回发射源方块的当前位置 if (this.state.sourceBlock && this.state.sourceBlock.isValid) { // 动态获取方块的当前世界位置 return this.state.sourceBlock.worldPosition.clone(); } // 如果方块节点无效,回退到起始位置 return this.state.startPosition; } /** * 获取动态返回目标位置(方块当前位置) */ public getDynamicReturnTarget(): Vec3 | null { if (this.state.sourceBlock && this.state.sourceBlock.isValid) { return this.state.sourceBlock.worldPosition.clone(); } return null; } /** * 为返回阶段重新初始化轨道 * @param currentPos 当前位置(新的发射点) * @param targetPos 目标位置(方块位置) */ public reinitializeForReturn(currentPos: Vec3, targetPos: Vec3) { if (!this.config || !this.state) return; // 清除当前所有速度和运动 if (this.rigidBody) { this.rigidBody.linearVelocity = new Vec2(0, 0); this.rigidBody.angularVelocity = 0; } // 计算从当前位置到目标位置的方向 const direction = targetPos.clone().subtract(currentPos).normalize(); // 重新设置状态 this.state.startPosition = currentPos.clone(); this.state.targetPosition = targetPos.clone(); this.state.initialVelocity = direction.clone().multiplyScalar(this.config.speed); this.state.currentVelocity = direction.clone().multiplyScalar(this.config.speed); this.state.elapsedTime = 0; // 重新初始化弧线轨道参数 if (this.config.type === 'arc') { this.arcDir = direction.clone(); this.arcTargetDir = direction.clone(); } // 清除路径记录,开始新的返回轨道 this.state.flightPath = [currentPos.clone()]; this.state.returnPathIndex = -1; this.state.lastRecordTime = 0; console.log(`[BulletTrajectory] 重新初始化返回轨道: ${currentPos} -> ${targetPos}`); } /** * 验证配置 */ 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; } }