| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339 |
- import { _decorator, Component, Node, Vec2, Vec3, RigidBody2D, find } from 'cc';
- const { ccclass, property } = _decorator;
- /**
- * 弹道控制器
- * 负责控制子弹的运动轨迹
- */
- export interface BulletTrajectoryConfig {
- type: 'straight' | 'parabolic' | 'arc' | 'homing_arc'; // 弹道类型
- speed: number; // 初始速度
- gravity: number; // 重力影响
- arcHeight: 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_arc') {
- 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':
- case 'arc':
- case 'homing_arc':
- // 计算抛物线初始速度
- const velocity = this.calculateParabolicVelocity();
- this.rigidBody.linearVelocity = velocity;
- this.state.currentVelocity.set(velocity.x, velocity.y, 0);
- break;
- }
- }
-
- /**
- * 计算抛物线初始速度
- */
- private calculateParabolicVelocity(): Vec2 {
- const direction = this.state.initialVelocity.clone().normalize();
- const speed = this.config.speed;
-
- // 基础抛物线速度
- let vx = direction.x * speed;
- let vy = direction.y * speed;
-
- // 如果有弧线高度,调整y轴速度
- if (this.config.arcHeight > 0) {
- // 计算到达弧线顶点需要的额外速度
- const timeToApex = Math.abs(vx) / speed; // 简化计算
- const extraVy = Math.sqrt(2 * Math.abs(this.config.gravity * 9.8) * this.config.arcHeight);
- vy += extraVy;
- }
-
- 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 'arc':
- this.updateArcTrajectory(dt);
- break;
- case 'homing_arc':
- 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 updateArcTrajectory(dt: number) {
- // 弧线弹道结合了直线和抛物线特性
- const t = this.state.elapsedTime;
- const arcPeriod = 2.0; // 弧线周期
- const arcFactor = Math.sin(t * Math.PI / arcPeriod) * this.config.arcHeight * 0.1;
-
- const currentVel = this.rigidBody.linearVelocity;
- this.rigidBody.linearVelocity = new Vec2(
- currentVel.x,
- currentVel.y + arcFactor * dt
- );
- }
-
- /**
- * 更新追踪弹道
- */
- private updateHomingTrajectory(dt: number) {
- // 先按抛物线运动
- this.updateParabolicTrajectory(dt);
-
- // 追踪延迟后开始追踪
- if (this.homingTimer > 0) {
- this.homingTimer -= dt;
- return;
- }
-
- if (!this.targetNode || !this.targetNode.isValid) {
- this.findTarget(); // 重新寻找目标
- return;
- }
-
- // 计算追踪力
- const currentPos = this.node.worldPosition;
- const targetPos = this.targetNode.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.arcHeight < 0) return false;
- if (config.homingStrength < 0 || config.homingStrength > 1) return false;
- if (config.homingDelay < 0) return false;
-
- return true;
- }
- }
|