| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847 |
- import { _decorator, Component, Node, Vec2, Vec3, RigidBody2D, find } from 'cc';
- import { EnemyAttackStateManager } from '../EnemyAttackStateManager';
- 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; // 目标方向(最终方向)
- // === Guided Trajectory (更强自动导航,可拐弯并切换目标) ===
- private guidedDir: Vec3 = null; // 当前引导方向
- private guidedTargetDir: 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 'homing':
- this.rigidBody.linearVelocity = new Vec2(
- this.state.initialVelocity.x,
- this.state.initialVelocity.y
- );
- break;
-
- case 'guided': {
- // 参考 arc:初始方向加入随机偏移,但拐弯能力更强
- const baseDir = this.state.initialVelocity.clone().normalize();
- const sign = Math.random() < 0.5 ? 1 : -1;
- const rad = 35 * Math.PI / 180 * sign; // 比 arc 略小的初始偏移,便于后续强导航
- const c = Math.cos(rad);
- const s = Math.sin(rad);
- const offsetDir = new Vec3(
- baseDir.x * c - baseDir.y * s,
- baseDir.x * s + baseDir.y * c,
- 0
- ).normalize();
- this.guidedDir = offsetDir.clone();
- this.guidedTargetDir = baseDir.clone();
- // 设置初速度
- 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;
- }
- case 'arc': {
- // 计算带 45° 随机偏移的初始方向
- const baseDir = this.state.initialVelocity.clone().normalize();
- const signArc = Math.random() < 0.5 ? 1 : -1;
- const radArc = 45 * Math.PI / 180 * signArc;
- const cosArc = Math.cos(radArc);
- const sinArc = Math.sin(radArc);
- const offsetDir = new Vec3(
- baseDir.x * cosArc - baseDir.y * sinArc,
- baseDir.x * sinArc + baseDir.y * cosArc,
- 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 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;
- }
- /**
- * 检查场上是否仍有“真实存在”的敌人
- * 不受隐身影响:隐身敌人仍算存在;只有全部死亡/销毁才返回false
- */
- private hasAliveEnemies(): boolean {
- // 优先使用攻击状态管理器的敌人总数(包含隐身敌人)
- const mgr = EnemyAttackStateManager.getInstance();
- if (mgr && typeof mgr.getEnemyCount === 'function') {
- if (mgr.getEnemyCount() > 0) return true;
- }
- // 回退:扫描场景节点
- const enemyContainer = find('Canvas/GameLevelUI/enemyContainer');
- if (!enemyContainer) return false;
- const enemies = enemyContainer.children.filter(child => child.isValid && child.active && this.isEnemyNode(child));
- return enemies.length > 0;
- }
-
- 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 'homing':
- this.updateHomingTrajectory(dt);
- break;
- case 'guided':
- this.updateGuidedTrajectory(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 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) && !this.hasAliveEnemies()) {
- const lifecycle = this.getComponent('BulletLifecycle') as any;
- if (this.rigidBody) {
- this.rigidBody.linearVelocity = new Vec2(0, 0);
- }
- if (lifecycle && typeof lifecycle.forceDestroy === 'function') {
- lifecycle.forceDestroy();
- } else {
- // 兜底:销毁节点
- if (this.node && this.node.isValid) this.node.destroy();
- }
- return;
- }
- }
- // 检查是否到达目标位置(爆炸武器和回旋镖都适用,但处理方式不同)
- 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);
- }
- /**
- * 更新 guided 轨迹:强导航、顺滑拐弯与目标切换
- */
- private updateGuidedTrajectory(dt: number) {
- if (!this.guidedDir || !this.guidedTargetDir) return;
- // 动态追踪与目标切换:优先当前锁定;失效或消失则寻找最近目标
- if (!this.targetNode || !this.targetNode.isValid) {
- this.findTarget();
- // 若仍无目标且场上没有任何存活敌人,则立刻结束生命周期
- if ((!this.targetNode || !this.targetNode.isValid) && !this.hasAliveEnemies()) {
- const lifecycle = this.getComponent('BulletLifecycle') as any;
- if (this.rigidBody) {
- this.rigidBody.linearVelocity = new Vec2(0, 0);
- }
- if (lifecycle && typeof lifecycle.forceDestroy === 'function') {
- lifecycle.forceDestroy();
- } else {
- if (this.node && this.node.isValid) this.node.destroy();
- }
- return;
- }
- }
- const currentPos = this.node.worldPosition;
- let targetPos: Vec3 | null = null;
- if (this.targetNode && this.targetNode.isValid) {
- targetPos = this.targetNode.worldPosition;
- } else if (this.state.targetPosition) {
- targetPos = this.state.targetPosition;
- }
- // 若仍无目标,保持原方向匀速飞行
- if (!targetPos) {
- if (this.rigidBody) {
- this.rigidBody.linearVelocity = new Vec2(this.guidedDir.x * this.config.speed, this.guidedDir.y * this.config.speed);
- }
- return;
- }
- // 期望方向(纯追踪)
- const dirToTarget = targetPos.clone().subtract(currentPos).normalize();
- const dist = Vec3.distance(currentPos, targetPos);
- // 动态平滑:远距离更平滑,近距离响应更快
- const t = this.state.elapsedTime;
- let smooth: number;
- if (dist > 350) {
- smooth = t < 0.6 ? 0.15 : 0.18; // 前期更柔和
- } else if (dist > 180) {
- smooth = 0.24; // 中段略增强响应
- } else if (dist > 90) {
- smooth = 0.36; // 接近时明显加快
- } else {
- smooth = 0.52; // 临近目标快速贴合
- }
- const blended = new Vec3(
- this.guidedTargetDir.x + (dirToTarget.x - this.guidedTargetDir.x) * smooth,
- this.guidedTargetDir.y + (dirToTarget.y - this.guidedTargetDir.y) * smooth,
- 0
- ).normalize();
- this.guidedTargetDir.set(blended);
- // 根据角误差与距离动态提升转向速率(构造“导弹投掷”前平滑、末段急拐”手感)
- const dot = Math.max(-1, Math.min(1, this.guidedDir.x * this.guidedTargetDir.x + this.guidedDir.y * this.guidedTargetDir.y));
- const angleErr = Math.acos(dot); // [0, π]
- const baseRotate = (this.config.rotateSpeed ?? 0.8) * dt;
- let turnScale: number;
- if (dist > 350) {
- turnScale = 0.35; // 远处很平滑
- } else if (dist > 180) {
- turnScale = 0.6; // 中段加速但仍平滑
- } else if (dist > 90) {
- turnScale = 0.9; // 接近目标时显著加快
- } else {
- turnScale = 1.5; // 末段急拐,形成导弹俯冲感觉
- }
- const angleScale = 0.8 + (angleErr / Math.PI) * 1.4;
- // 末段大角误差额外加成,增强“急转”质感
- const lateTurnBonus = (dist < 70 && angleErr > (50 * Math.PI / 180)) ? 1.6 : 1.0;
- let rotateFactor = baseRotate * turnScale * angleScale * lateTurnBonus;
- // 限制范围,确保数值稳定
- rotateFactor = Math.min(0.95, Math.max(0.015, rotateFactor));
- // 使用带符号角度的旋转以避免过度插值导致的打圈
- // 计算带符号角误差 [-π, π]
- const dotClamped = Math.max(-1, Math.min(1, this.guidedDir.x * this.guidedTargetDir.x + this.guidedDir.y * this.guidedTargetDir.y));
- const crossZ = this.guidedDir.x * this.guidedTargetDir.y - this.guidedDir.y * this.guidedTargetDir.x;
- const signedAngle = Math.atan2(crossZ, dotClamped);
- // 以 rotateFactor 作为“最大步进”,限制每帧转向幅度,避免来回过冲产生自转
- const maxTurn = Math.min(0.95, Math.max(0.01, rotateFactor)) * Math.PI; // 将插值因子映射到弧度步进
- const clampedTurn = Math.max(-maxTurn, Math.min(maxTurn, signedAngle));
- // 近距稳定锁定:很近且角误差很小,直接对准避免绕圈
- if (dist < 50 && Math.abs(signedAngle) < (12 * Math.PI / 180)) {
- this.guidedDir.set(this.guidedTargetDir);
- } else {
- const c = Math.cos(clampedTurn);
- const s = Math.sin(clampedTurn);
- const rotated = new Vec3(
- this.guidedDir.x * c - this.guidedDir.y * s,
- this.guidedDir.x * s + this.guidedDir.y * c,
- 0
- ).normalize();
- this.guidedDir.set(rotated);
- }
- // 更新速度
- if (this.rigidBody) {
- this.rigidBody.linearVelocity = new Vec2(this.guidedDir.x * this.config.speed, this.guidedDir.y * this.config.speed);
- } else {
- const displacement = this.guidedDir.clone().multiplyScalar(this.config.speed * dt);
- this.node.worldPosition = this.node.worldPosition.add(displacement);
- }
- this.state.currentVelocity.set(this.guidedDir.x * this.config.speed, this.guidedDir.y * this.config.speed, 0);
- // 近距命中(对齐爆炸型的处理)
- const lifecycle = this.getComponent('BulletLifecycle') as any;
- const hitEffect = this.getComponent('BulletHitEffect') as any;
- const isExplosion = hitEffect && typeof (hitEffect as any).hasExplosionEffect === 'function'
- ? (hitEffect as any).hasExplosionEffect()
- : false;
- if (this.targetNode && this.targetNode.isValid) {
- const hitRadius = 45;
- const d = Vec3.distance(currentPos, this.targetNode.worldPosition);
- if (d <= hitRadius) {
- if (this.rigidBody) this.rigidBody.linearVelocity = new Vec2(0, 0);
- if (isExplosion) {
- if (hitEffect && typeof hitEffect.processHit === 'function') {
- hitEffect.processHit(this.node, currentPos);
- }
- if (lifecycle && typeof lifecycle.onHit === 'function') {
- lifecycle.onHit(this.node);
- }
- } else {
- if (hitEffect && typeof hitEffect.processHit === 'function') {
- hitEffect.processHit(this.targetNode, currentPos);
- }
- if (lifecycle && typeof lifecycle.onHit === 'function') {
- lifecycle.onHit(this.targetNode);
- }
- }
- return;
- }
- } else {
- // 目标消失:立刻尝试找新目标并继续引导
- this.findTarget();
- }
- }
-
- /**
- * 获取当前速度
- */
- 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;
- }
- }
|