| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443 |
- import { _decorator, Component, Node, Vec3, Vec2, find, UITransform, RigidBody2D } from 'cc';
- import { BulletTrajectory } from './BulletTrajectory';
- import { BulletLifecycleConfig } from '../../Core/ConfigManager';
- const { ccclass, property } = _decorator;
- /**
- * 子弹生命周期控制器
- * 负责管理子弹的生存时间和销毁条件
- */
- export interface LifecycleState {
- elapsedTime: number; // 已存活时间
- hitCount: number; // 命中次数
- ricochetLeft: number; // 剩余弹射次数
- pierceLeft: number; // 剩余穿透次数
- travelDistance: number; // 已飞行距离
- phase: 'active' | 'returning' | 'effect' | 'destroyed'; // 生命周期阶段
- shouldDestroy: boolean; // 是否应该销毁
- startPosition: Vec3; // 起始位置
- returnTimer: number; // 返回计时器
- }
- @ccclass('BulletLifecycle')
- export class BulletLifecycle extends Component {
- private config: BulletLifecycleConfig = null;
- private state: LifecycleState = null;
- private lastPosition: Vec3 = new Vec3();
-
- /**
- * 初始化生命周期
- */
- public init(config: BulletLifecycleConfig, startPos: Vec3) {
- console.log(`[BulletLifecycle] 初始化子弹生命周期 - 节点: ${this.node.name}, 配置类型: ${config.type}, 最大生命: ${config.maxLifetime}, 最大射程: ${config.maxRange}`);
-
- this.config = { ...config };
-
- this.state = {
- elapsedTime: 0,
- hitCount: 0,
- ricochetLeft: config.ricochetCount,
- pierceLeft: config.penetration,
- travelDistance: 0,
- phase: 'active',
- shouldDestroy: false,
- startPosition: startPos.clone(),
- returnTimer: config.returnDelay || 0
- };
-
- this.lastPosition = startPos.clone();
- console.log(`[BulletLifecycle] 子弹生命周期初始化完成 - 节点: ${this.node.name}, 起始位置: (${startPos.x}, ${startPos.y}), 当前位置: (${this.node.worldPosition.x}, ${this.node.worldPosition.y}), lastPosition: (${this.lastPosition.x}, ${this.lastPosition.y})`);
- }
-
- /**
- * 处理命中事件
- */
- public onHit(hitNode: Node): boolean {
- if (!this.config || !this.state) return true;
-
- this.state.hitCount++;
-
- switch (this.config.type) {
- case 'hit_destroy':
- return this.handleHitDestroy();
-
- case 'range_limit':
- return this.handleRangeLimit();
-
- case 'ricochet_counter':
- return this.handleRicochetCounter();
-
- case 'ground_impact':
- case 'ground_impact_with_effect':
- return this.handleGroundImpact(hitNode);
-
- case 'return_trip':
- return this.handleReturnTrip();
-
- case 'target_impact':
- return this.handleTargetImpact(hitNode);
-
- default:
- return true; // 默认销毁
- }
- }
-
- /**
- * 处理命中即销毁逻辑
- */
- private handleHitDestroy(): boolean {
- this.state.shouldDestroy = true;
- return true;
- }
-
- /**
- * 处理射程限制逻辑
- */
- private handleRangeLimit(): boolean {
- // 穿透逻辑
- if (this.state.pierceLeft > 0) {
- this.state.pierceLeft--;
- return false; // 不销毁,继续飞行
- } else {
- this.state.shouldDestroy = true;
- return true;
- }
- }
-
- /**
- * 处理弹射计数逻辑
- */
- private handleRicochetCounter(): boolean {
- if (this.state.ricochetLeft > 0) {
- this.state.ricochetLeft--;
-
- // 触发弹射
- const trajectory = this.getComponent(BulletTrajectory);
- if (trajectory) {
- // BulletTrajectory会处理方向改变
- }
-
- return false; // 不销毁,继续弹射
- } else {
- this.state.shouldDestroy = true;
- return true;
- }
- }
-
- /**
- * 处理地面撞击逻辑
- */
- private handleGroundImpact(hitNode: Node): boolean {
- const isGround = this.isGroundNode(hitNode);
-
- if (isGround) {
- // 进入效果阶段
- this.state.phase = 'effect';
-
- // 延迟销毁,等待效果结束
- if (this.config.effectDuration && this.config.effectDuration > 0) {
- this.scheduleOnce(() => {
- this.state.shouldDestroy = true;
- }, this.config.effectDuration);
- } else {
- this.state.shouldDestroy = true;
- }
-
- return true;
- } else {
- // 延迟销毁,确保爆炸的 0.1 s 延迟能正常触发
- this.scheduleOnce(() => {
- this.state.shouldDestroy = true;
- }, 0.2);
- // === 立即冻结子弹运动,避免命中后继续绕圈 ===
- const trajectory = this.getComponent(BulletTrajectory);
- if (trajectory) {
- trajectory.enabled = false; // 停止后续 update
- }
- const rigidBody = this.getComponent(RigidBody2D);
- if (rigidBody) {
- rigidBody.linearVelocity = new Vec2(0, 0);
- rigidBody.angularVelocity = 0;
- }
-
- return true;
- }
- }
-
- /**
- * 处理回旋镖逻辑
- */
- private handleReturnTrip(): boolean {
- if (this.state.phase === 'active') {
- // 首次命中立即开始返程,不再依据pierceLeft
- this.startReturn();
- return false; // 不销毁
- } else if (this.state.phase === 'returning') {
- // 返回途中命中,仅造成伤害不销毁
- return false;
- }
- return false;
- }
-
- /**
- * 处理目标撞击逻辑(导弹)
- */
- private handleTargetImpact(hitNode: Node): boolean {
- const isEnemy = this.isEnemyNode(hitNode);
-
- if (isEnemy) {
- this.state.shouldDestroy = true;
- return true;
- }
-
- // 如果不是敌人,继续飞行(导弹不会被其他物体阻挡)
- return false;
- }
-
- /**
- * 判断是否为地面节点
- */
- private isGroundNode(node: Node): boolean {
- const name = node.name.toLowerCase();
- return name.includes('ground') ||
- name.includes('wall') ||
- name.includes('地面') ||
- name.includes('墙');
- }
-
- /**
- * 判断是否为敌人节点
- */
- 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) {
- console.log(`[BulletLifecycle] update跳过 - 节点: ${this.node.name}, config存在: ${!!this.config}, state存在: ${!!this.state}`);
- return;
- }
-
- this.state.elapsedTime += dt;
-
- // 更新飞行距离
- this.updateTravelDistance();
-
- // 检查各种销毁条件
- this.checkDestroyConditions();
-
- // 处理特殊逻辑
- this.updateSpecialLogic(dt);
-
- // 如果需要销毁,执行销毁
- if (this.state.shouldDestroy) {
- console.log(`[BulletLifecycle] 准备销毁子弹 - 节点: ${this.node.name}, 存活时间: ${this.state.elapsedTime}`);
- this.destroyBullet();
- }
- }
-
- /**
- * 更新飞行距离
- */
- private updateTravelDistance() {
- const currentPos = this.node.worldPosition;
- const distance = Vec3.distance(this.lastPosition, currentPos);
- console.log(`[BulletLifecycle] 更新飞行距离 - 节点: ${this.node.name}, 上次位置: (${this.lastPosition.x}, ${this.lastPosition.y}), 当前位置: (${currentPos.x}, ${currentPos.y}), 本次距离: ${distance}, 总距离: ${this.state.travelDistance} -> ${this.state.travelDistance + distance}`);
- this.state.travelDistance += distance;
- this.lastPosition.set(currentPos);
- }
-
- /**
- * 检查销毁条件
- */
- private checkDestroyConditions() {
- console.log(`[BulletLifecycle] 检查销毁条件 - 节点: ${this.node.name}, 存活时间: ${this.state.elapsedTime}, 最大生命: ${this.config.maxLifetime}, 飞行距离: ${this.state.travelDistance}, 最大射程: ${this.config.maxRange}`);
-
- // 检查时间限制
- if (this.state.elapsedTime >= this.config.maxLifetime) {
- console.log(`[BulletLifecycle] 子弹因超时被销毁 - 节点: ${this.node.name}, 存活时间: ${this.state.elapsedTime} >= 最大生命: ${this.config.maxLifetime}`);
- this.state.shouldDestroy = true;
- return;
- }
-
- // === 射程限制逻辑优化 ===
- if (this.config.maxRange && this.state.travelDistance >= this.config.maxRange) {
- console.log(`[BulletLifecycle] 子弹达到最大射程 - 节点: ${this.node.name}, 飞行距离: ${this.state.travelDistance} >= 最大射程: ${this.config.maxRange}, 类型: ${this.config.type}`);
- if (this.config.type === 'range_limit') {
- console.log(`[BulletLifecycle] 子弹因射程限制被销毁 - 节点: ${this.node.name}`);
- this.state.shouldDestroy = true;
- } else if (this.config.type === 'return_trip') {
- // 回旋镖:首次超距时开始返回;返回途中不再因射程销毁
- if (this.state.phase === 'active') {
- console.log(`[BulletLifecycle] 回旋镖开始返回 - 节点: ${this.node.name}`);
- this.startReturn();
- }
- }
- // 其他生命周期类型忽略射程限制
- return;
- }
-
- // 检查越界
- const outOfBounds = this.checkOutOfBounds();
- console.log(`[BulletLifecycle] 越界检查结果 - 节点: ${this.node.name}, 是否越界: ${outOfBounds}, 位置: (${this.node.worldPosition.x}, ${this.node.worldPosition.y})`);
- if (outOfBounds) {
- if (this.config.type === 'return_trip' && this.state.phase === 'active') {
- console.log(`[BulletLifecycle] 回旋镖因越界开始返回 - 节点: ${this.node.name}`);
- this.startReturn();
- } else {
- console.log(`[BulletLifecycle] 子弹因越界被销毁 - 节点: ${this.node.name}, 位置: (${this.node.worldPosition.x}, ${this.node.worldPosition.y})`);
- this.state.shouldDestroy = true;
- }
- return;
- }
- }
-
- /**
- * 更新特殊逻辑
- */
- private updateSpecialLogic(dt: number) {
- switch (this.config.type) {
- case 'return_trip':
- this.updateReturnTrip(dt);
- break;
- }
- }
-
- /**
- * 更新回旋镖逻辑
- */
- private updateReturnTrip(dt: number) {
- if (this.state.phase === 'active' && this.state.returnTimer > 0) {
- this.state.returnTimer -= dt;
- if (this.state.returnTimer <= 0) {
- this.startReturn();
- }
- } else if (this.state.phase === 'returning') {
- // 检查是否返回到原点
- const distanceToOrigin = Vec3.distance(this.node.worldPosition, this.state.startPosition);
- if (distanceToOrigin <= 50) { // 50单位的容差
- this.state.shouldDestroy = true;
- }
- }
- }
-
- /**
- * 开始返回
- */
- private startReturn() {
- this.state.phase = 'returning';
-
- const trajectory = this.getComponent(BulletTrajectory);
- if (trajectory) {
- trajectory.setTargetPosition(this.state.startPosition);
- trajectory.reverseDirection();
- }
- }
-
- /**
- * 检查越界
- */
- private checkOutOfBounds(): boolean {
- // 优先使用 GameArea 的可视区域(若存在)
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- let bounding = null;
- if (gameArea) {
- const tr = gameArea.getComponent(UITransform);
- if (tr) {
- bounding = tr.getBoundingBoxToWorld();
- console.log(`[BulletLifecycle] 使用GameArea边界 - 节点: ${this.node.name}, 边界: (${bounding.xMin}, ${bounding.yMin}) 到 (${bounding.xMax}, ${bounding.yMax})`);
- }
- }
- // fallback => Canvas 整体区域
- if (!bounding) {
- const canvas = find('Canvas');
- if (canvas) {
- const tr = canvas.getComponent(UITransform);
- if (tr) {
- bounding = tr.getBoundingBoxToWorld();
- console.log(`[BulletLifecycle] 使用Canvas边界 - 节点: ${this.node.name}, 边界: (${bounding.xMin}, ${bounding.yMin}) 到 (${bounding.xMax}, ${bounding.yMax})`);
- }
- }
- }
- // 若无法获取区域,则不做越界销毁
- if (!bounding) {
- console.log(`[BulletLifecycle] 无法获取边界信息 - 节点: ${this.node.name}, 不进行越界检查`);
- return false;
- }
- // 允许一定的 margin
- const margin = 300; // 扩大容差,防止大速度时瞬移出界
- const pos = this.node.worldPosition;
-
- const outOfBounds = pos.x < bounding.xMin - margin ||
- pos.x > bounding.xMax + margin ||
- pos.y < bounding.yMin - margin ||
- pos.y > bounding.yMax + margin;
-
- console.log(`[BulletLifecycle] 越界详细检查 - 节点: ${this.node.name}, 位置: (${pos.x}, ${pos.y}), 边界(含margin): (${bounding.xMin - margin}, ${bounding.yMin - margin}) 到 (${bounding.xMax + margin}, ${bounding.yMax + margin}), 结果: ${outOfBounds}`);
-
- return outOfBounds;
- }
-
- /**
- * 销毁子弹
- */
- private destroyBullet() {
- console.log(`[BulletLifecycle] 执行销毁子弹 - 节点: ${this.node.name}, 存活时间: ${this.state.elapsedTime}, 飞行距离: ${this.state.travelDistance}`);
- this.node.destroy();
- console.log(`[BulletLifecycle] 子弹已销毁 - 节点: ${this.node.name}`);
- }
-
- /**
- * 获取生命周期状态
- */
- public getState(): LifecycleState {
- return this.state;
- }
-
- /**
- * 检查是否应该销毁
- */
- public shouldDestroy(): boolean {
- return this.state ? this.state.shouldDestroy : true;
- }
-
- /**
- * 强制销毁
- */
- public forceDestroy() {
- this.state.shouldDestroy = true;
- }
-
- /**
- * 获取剩余生命时间
- */
- public getRemainingLifetime(): number {
- if (!this.config || !this.state) return 0;
- return Math.max(0, this.config.maxLifetime - this.state.elapsedTime);
- }
-
- /**
- * 验证配置
- */
- public static validateConfig(config: BulletLifecycleConfig): boolean {
- if (!config) return false;
-
- if (config.maxLifetime <= 0) return false;
- if (config.penetration < 0) return false;
- if (config.ricochetCount < 0) return false;
- if (config.maxRange && config.maxRange <= 0) return false;
- if (config.effectDuration && config.effectDuration < 0) return false;
- if (config.returnDelay && config.returnDelay < 0) return false;
-
- return true;
- }
- }
|