| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402 |
- import { _decorator, Component, Node, Vec2, Vec3, UITransform, Collider2D, Contact2DType, IPhysics2DContact, RigidBody2D, Prefab, instantiate, find, CircleCollider2D, JsonAsset, ERigidBody2DType } from 'cc';
- import { PhysicsManager } from '../Core/PhysicsManager';
- import { WeaponBullet, BulletInitData } from './WeaponBullet';
- import { WeaponConfig } from '../Core/ConfigManager';
- import EventBus, { GameEvents } from '../Core/EventBus';
- import { PersistentSkillManager } from '../FourUI/SkillSystem/PersistentSkillManager';
- import { BallControllerConfig } from '../Core/ConfigManager';
- import { WeaponInfo } from './BlockSelection/WeaponInfo';
- import { BlockInfo } from './BlockSelection/BlockInfo';
- import { BallAni } from '../Animations/BallAni';
- import { JsonConfigLoader } from '../Core/JsonConfigLoader';
- const { ccclass, property } = _decorator;
- @ccclass('BallController')
- export class BallController extends Component {
- // 球的预制体
- @property({
- type: Prefab,
- tooltip: '拖拽Ball预制体到这里'
- })
- public ballPrefab: Prefab = null;
- // 已放置方块容器节点
- @property({
- type: Node,
- tooltip: '拖拽PlacedBlocks节点到这里(Canvas/GameLevelUI/GameArea/PlacedBlocks)'
- })
- public placedBlocksContainer: Node = null;
- // 球控制器配置文件
- // @property({
- // type: JsonAsset,
- // tooltip: '拖拽ballController.json配置文件到这里'
- // })
- // public ballControllerConfig: JsonAsset = null; // 已改为动态加载
- // 球的移动速度(从配置文件加载)
- public baseSpeed: number = 60;
- public currentSpeed: number = 60;
-
- // 反弹随机偏移最大角度(弧度)(从配置文件加载)
- public maxReflectionRandomness: number = 0.2;
-
- // 当前活动的球
- private activeBall: Node = null;
- // 球的方向向量
- private direction: Vec2 = new Vec2();
-
- // GameArea区域边界
- private gameBounds = {
- left: 0,
- right: 0,
- top: 0,
- bottom: 0
- };
- // 球的半径
- private radius: number = 0;
- // 配置数据
- private config: BallControllerConfig = null;
- // 是否已初始化
- private initialized: boolean = false;
-
- // 子弹预制体
- @property({
- type: Prefab,
- tooltip: '拖拽子弹预制体到这里'
- })
- public bulletPrefab: Prefab = null;
- // 小球是否已开始运动
- private ballStarted: boolean = false;
- // 小球暂停时记录的速度
- private pausedVelocity: Vec2 = new Vec2();
- // 所有小球暂停时记录的速度(包括主球和额外球)
- private allBallsPausedVelocities: Map<Node, Vec2> = new Map();
- // 标记是否处于暂停状态
- private isPaused: boolean = false;
- // 在类字段区添加
- private blockFireCooldown: Map<string, number> = new Map();
- private FIRE_COOLDOWN = 0.05;
- // 防围困机制配置(从配置文件加载)
- public antiTrapTimeWindow: number = 5.0;
- public antiTrapHitThreshold: number = 5;
- public deflectionAttemptThreshold: number = 3;
- public antiTrapDeflectionMultiplier: number = 3.0;
-
- // 增强防围困机制配置
- @property({
- tooltip: '振荡检测时间窗口(秒):检测小球往复运动的时间范围'
- })
- public oscillationTimeWindow: number = 3.0;
-
- @property({
- tooltip: '方向改变阈值:触发振荡检测的方向改变次数'
- })
- public directionChangeThreshold: number = 4;
-
- @property({
- tooltip: '位置历史记录数量:用于检测往复运动的位置样本数'
- })
- public positionHistorySize: number = 20;
-
- @property({
- tooltip: '振荡距离阈值:判定为往复运动的最小距离范围'
- })
- public oscillationDistanceThreshold: number = 100;
-
- // 测试模式开关
- @property({
- tooltip: '启用测试模式:小球只会向上/下/左/右四个基本方向移动,便于测试防围困机制'
- })
- public testMode: boolean = true;
- // 小球位置检查配置
- @property({
- tooltip: '启用小球位置检查:定期检查小球是否在游戏区域内,如果不在则找回'
- })
- public enableBallPositionCheck: boolean = true;
-
- @property({
- tooltip: '位置检查间隔(秒):多久检查一次小球位置'
- })
- public positionCheckInterval: number = 2.0;
-
- @property({
- tooltip: '位置检查边界扩展(像素):检查边界比游戏区域稍大,避免误判'
- })
- public positionCheckBoundaryExtension: number = 50;
- // 防围困机制状态
- private ballHitHistory: Map<string, number[]> = new Map(); // 记录每个球的撞击时间历史
- private ballPhaseThrough: Map<string, number> = new Map(); // 记录每个球的穿透结束时间
- private ballDeflectionAttempts: Map<string, number> = new Map(); // 记录每个球的偏移尝试次数
-
- // 增强防围困机制:运动模式检测
- private ballPositionHistory: Map<string, Vec2[]> = new Map(); // 记录小球位置历史
- private ballDirectionHistory: Map<string, Vec2[]> = new Map(); // 记录小球方向历史
- private ballOscillationDetection: Map<string, {
- lastDirectionChange: number,
- directionChangeCount: number,
- oscillationAxis: 'horizontal' | 'vertical' | 'none',
- oscillationStartTime: number
- }> = new Map(); // 振荡检测数据
- // 带尾部特效的子弹容器预制体
- @property({
- type: Prefab,
- tooltip: '拖拽带尾部特效的子弹容器预制体到这里(例如 PelletContainer)'
- })
- public bulletContainerPrefab: Prefab = null;
- // 正在被拖拽的方块集合
- private draggingBlocks: Set<Node> = new Set();
- // 小球位置检查相关变量
- private lastPositionCheckTime: number = 0; // 上次位置检查的时间
- async start() {
- // 如果没有指定placedBlocksContainer,尝试找到它
- if (!this.placedBlocksContainer) {
- this.placedBlocksContainer = find('Canvas/GameLevelUI/GameArea/PlacedBlocks');
- if (!this.placedBlocksContainer) {
- // 找不到PlacedBlocks节点,某些功能可能无法正常工作
- }
- }
-
-
- // 加载配置
- await this.loadConfig();
-
- // 只进行初始设置,不创建小球
- this.calculateGameBounds();
- // 监听游戏事件
- this.setupEventListeners();
-
- // 监听球速技能变化并更新球速
- this.updateBallSpeed();
- }
- /**
- * 设置事件监听器
- */
- // 加载配置
- private async loadConfig(): Promise<void> {
- try {
- this.config = await JsonConfigLoader.getInstance().loadConfig('ballController') as BallControllerConfig;
- this.applyConfig();
- console.log('[BallController] ✅ 配置文件通过JsonConfigLoader加载成功:', this.config);
- } catch (error) {
- console.error('[BallController] 加载配置文件失败:', error);
- this.useDefaultConfig();
- }
- }
- private useDefaultConfig(): void {
- // 使用默认配置
- this.config = {
- baseSpeed: 60,
- maxReflectionRandomness: 0.2,
- antiTrapTimeWindow: 5.0,
- antiTrapHitThreshold: 5,
- deflectionAttemptThreshold: 3,
- antiTrapDeflectionMultiplier: 3.0,
- FIRE_COOLDOWN: 0.05,
- ballRadius: 10,
- gravityScale: 0,
- linearDamping: 0,
- angularDamping: 0,
- colliderGroup: 1,
- colliderTag: 1,
- friction: 0,
- restitution: 1,
- safeDistance: 50,
- edgeOffset: 20,
- sensor: false,
- maxAttempts: 50
- };
- this.applyConfig();
- }
- // 应用配置
- private applyConfig() {
- if (!this.config) return;
-
- this.baseSpeed = this.config.baseSpeed;
- this.currentSpeed = this.config.baseSpeed;
- this.maxReflectionRandomness = this.config.maxReflectionRandomness;
- this.antiTrapTimeWindow = this.config.antiTrapTimeWindow;
- this.antiTrapHitThreshold = this.config.antiTrapHitThreshold;
- this.deflectionAttemptThreshold = this.config.deflectionAttemptThreshold;
- this.antiTrapDeflectionMultiplier = this.config.antiTrapDeflectionMultiplier;
- this.FIRE_COOLDOWN = this.config.FIRE_COOLDOWN;
-
- console.log('BallController配置已应用:', this.config);
- }
- // 从配置中获取参数值的辅助方法
- private getConfigValue<T>(key: keyof BallControllerConfig, defaultValue: T): T {
- return this.config && this.config[key] !== undefined ? this.config[key] as T : defaultValue;
- }
- // 配置参数的getter方法
- private get ballRadius(): number {
- return this.getConfigValue('ballRadius', 10);
- }
- private get gravityScale(): number {
- return this.getConfigValue('gravityScale', 0);
- }
- private get linearDamping(): number {
- return this.getConfigValue('linearDamping', 0);
- }
- private get angularDamping(): number {
- return this.getConfigValue('angularDamping', 0);
- }
- private get colliderGroup(): number {
- return this.getConfigValue('colliderGroup', 2);
- }
- private get colliderTag(): number {
- return this.getConfigValue('colliderTag', 1);
- }
- private get friction(): number {
- return this.getConfigValue('friction', 0);
- }
- private get restitution(): number {
- return this.getConfigValue('restitution', 1);
- }
- private get safeDistance(): number {
- return this.getConfigValue('safeDistance', 50);
- }
- private get edgeOffset(): number {
- return this.getConfigValue('edgeOffset', 20);
- }
- private get sensor(): boolean {
- return this.getConfigValue('sensor', false);
- }
- private get maxAttempts(): number {
- return this.getConfigValue('maxAttempts', 50);
- }
- private setupEventListeners() {
- const eventBus = EventBus.getInstance();
-
- // 监听暂停事件
- eventBus.on(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
- eventBus.on(GameEvents.GAME_PAUSE_SKILL_SELECTION, this.onGamePauseSkillSelectionEvent, this);
- eventBus.on(GameEvents.GAME_PAUSE_BLOCK_SELECTION, this.onGamePauseBlockSelectionEvent, this);
-
- // 监听恢复事件
- eventBus.on(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
- eventBus.on(GameEvents.GAME_RESUME_SKILL_SELECTION, this.onGameResumeSkillSelectionEvent, this);
- eventBus.on(GameEvents.GAME_RESUME_BLOCK_SELECTION, this.onGameResumeBlockSelectionEvent, this);
-
- // 监听重置球控制器事件
- eventBus.on(GameEvents.RESET_BALL_CONTROLLER, this.onResetBallControllerEvent, this);
-
- // 监听球创建事件
- eventBus.on(GameEvents.BALL_CREATE, this.onBallCreateEvent, this);
-
- // 监听球启动事件
- eventBus.on(GameEvents.BALL_START, this.onBallStartEvent, this);
-
- // 监听创建额外球事件
- eventBus.on(GameEvents.BALL_CREATE_ADDITIONAL, this.onBallCreateAdditionalEvent, this);
-
- // 监听子弹发射检查事件
- eventBus.on(GameEvents.BALL_FIRE_BULLET, this.onBallFireBulletEvent, this);
-
- // 监听方块拖拽开始事件
- eventBus.on(GameEvents.BLOCK_DRAG_START, this.onBlockDragStartEvent, this);
-
- // 监听方块拖拽结束事件
- eventBus.on(GameEvents.BLOCK_DRAG_END, this.onBlockDragEndEvent, this);
- }
- /**
- * 处理游戏暂停事件
- */
- private onGamePauseEvent() {
- console.log('[BallController] 接收到游戏暂停事件,暂停小球运动');
- this.pauseBall();
- }
- /**
- * 处理技能选择暂停事件(所有小球完全停止)
- */
- private onGamePauseSkillSelectionEvent() {
- console.log('[BallController] 接收到技能选择暂停事件,暂停所有小球运动');
- this.pauseAllBalls();
- }
- /**
- * 处理底板选择暂停事件(所有小球继续运动)
- */
- private onGamePauseBlockSelectionEvent() {
- console.log('[BallController] 接收到底板选择暂停事件,小球继续运动');
- // 底板选择时不暂停小球运动,只是标记游戏状态为暂停
- this.isPaused = true;
- }
- /**
- * 处理游戏恢复事件
- */
- private onGameResumeEvent() {
- console.log('[BallController] 接收到游戏恢复事件,恢复小球运动');
- this.resumeAllBalls();
- }
-
- /**
- * 处理技能选择恢复事件
- */
- private onGameResumeSkillSelectionEvent() {
- console.log('[BallController] 接收到技能选择恢复事件,恢复小球运动');
- this.resumeAllBalls();
- }
-
- /**
- * 处理底板选择恢复事件
- */
- private onGameResumeBlockSelectionEvent() {
- console.log('[BallController] 接收到底板选择恢复事件,恢复小球运动');
- this.resumeAllBalls();
- }
-
- /**
- * 处理重置球控制器事件
- */
- private onResetBallControllerEvent() {
- console.log('[BallController] 接收到重置球控制器事件');
- this.resetBallController();
- }
-
- /**
- * 处理球创建事件
- */
- private onBallCreateEvent() {
- console.log('[BallController] 接收到球创建事件');
- this.createBall();
- }
-
- /**
- * 处理球启动事件
- */
- private onBallStartEvent() {
- console.log('[BallController] 接收到球启动事件');
- this.startBall();
- }
-
- /**
- * 处理创建额外球事件
- */
- private onBallCreateAdditionalEvent() {
- console.log('[BallController] 接收到创建额外球事件');
- this.createAdditionalBall();
- }
-
- /**
- * 处理子弹发射检查事件
- */
- private onBallFireBulletEvent(blockNode: Node, fireWorldPos: Vec3) {
- // 如果游戏暂停,则不允许发射子弹
- if (this.isPaused) {
- console.log('[BallController] 游戏暂停中,阻止子弹发射');
- return;
- }
-
- // 如果游戏未暂停,则继续执行子弹发射逻辑
- this.fireBulletAt(blockNode, fireWorldPos);
- }
-
- /**
- * 处理方块拖拽开始事件
- */
- private onBlockDragStartEvent(data: { block: Node }) {
- if (data && data.block) {
- console.log('[BallController] 方块开始拖拽:', data.block.name, '路径:', this.getNodePath(data.block));
- this.draggingBlocks.add(data.block);
- console.log('[BallController] 当前拖拽方块数量:', this.draggingBlocks.size);
- }
- }
-
- /**
- * 处理方块拖拽结束事件
- */
- private onBlockDragEndEvent(data: { block: Node }) {
- if (data && data.block) {
- console.log('[BallController] 方块结束拖拽:', data.block.name, '路径:', this.getNodePath(data.block));
- const wasDeleted = this.draggingBlocks.delete(data.block);
- console.log('[BallController] 删除成功:', wasDeleted, '当前拖拽方块数量:', this.draggingBlocks.size);
- }
- }
-
- /**
- * 调试方法:显示当前拖拽的方块
- */
- private debugDraggingBlocks() {
- console.log('[BallController] 当前拖拽方块列表:');
- this.draggingBlocks.forEach((block, index) => {
- // console.log(` ${index + 1}. ${block.name} - 路径: ${this.getNodePath(block)} - 有效: ${block.isValid}`);
- });
- }
- // 计算游戏边界(使用GameArea节点)
- calculateGameBounds() {
- // 获取GameArea节点
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- if (!gameArea) {
- return;
- }
- const gameAreaUI = gameArea.getComponent(UITransform);
- if (!gameAreaUI) {
- return;
- }
- // 获取GameArea的尺寸
- const areaWidth = gameAreaUI.width;
- const areaHeight = gameAreaUI.height;
-
- // 获取GameArea的世界坐标位置
- const worldPos = gameArea.worldPosition;
- // 计算GameArea的世界坐标边界
- this.gameBounds.left = worldPos.x - areaWidth / 2;
- this.gameBounds.right = worldPos.x + areaWidth / 2;
- this.gameBounds.bottom = worldPos.y - areaHeight / 2;
- this.gameBounds.top = worldPos.y + areaHeight / 2;
-
- }
- // 创建小球
- createBall() {
- if (!this.ballPrefab) {
- console.error('[BallController] ballPrefab 未设置,无法创建小球');
- return;
- }
- // 实例化小球
- this.activeBall = instantiate(this.ballPrefab);
-
- if (!this.activeBall) {
- console.error('[BallController] 小球实例化失败');
- return;
- }
-
- // 将小球添加到GameArea中
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- if (gameArea) {
- gameArea.addChild(this.activeBall);
- } else {
- console.warn('[BallController] 未找到GameArea,将小球添加到当前节点');
- this.node.addChild(this.activeBall);
- }
- // 随机位置小球
- this.positionBallRandomly();
- // 设置球的半径
- const transform = this.activeBall.getComponent(UITransform);
- if (transform) {
- this.radius = transform.width / 2;
- } else {
- this.radius = 25; // 默认半径
- }
- // 确保有碰撞组件
- this.setupCollider();
- // 注意:不在这里初始化方向,等待 startBall() 调用
- this.initialized = true;
- }
-
- // 创建额外的小球(不替换现有的小球)
- public createAdditionalBall() {
- if (!this.ballPrefab) {
- console.error('无法创建额外小球:ballPrefab 未设置');
- return;
- }
- // 实例化新的小球
- const newBall = instantiate(this.ballPrefab);
- newBall.name = 'AdditionalBall';
-
- // 将小球添加到GameArea中
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- if (gameArea) {
- gameArea.addChild(newBall);
- } else {
- this.node.addChild(newBall);
- }
- // 随机位置小球
- this.positionAdditionalBall(newBall);
- // 设置球的碰撞组件
- this.setupBallCollider(newBall);
-
- // 设置初始方向和速度
- this.initializeBallDirection(newBall);
-
- console.log('创建了额外的小球');
- return newBall;
- }
- // 为额外小球设置随机位置
- private positionAdditionalBall(ball: Node) {
- if (!ball) return;
- const transform = ball.getComponent(UITransform);
- const ballRadius = transform ? transform.width / 2 : this.ballRadius;
-
- // 计算可生成的范围(考虑小球半径,避免生成在边缘)
- const minX = this.gameBounds.left + ballRadius + this.edgeOffset;
- const maxX = this.gameBounds.right - ballRadius - this.edgeOffset;
- const minY = this.gameBounds.bottom + ballRadius + this.edgeOffset;
- const maxY = this.gameBounds.top - ballRadius - this.edgeOffset;
- // 获取GameArea节点
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- if (!gameArea) {
- return;
- }
-
- // 随机生成位置
- const randomX = Math.random() * (maxX - minX) + minX;
- const randomY = Math.random() * (maxY - minY) + minY;
-
- // 将世界坐标转换为相对于GameArea的本地坐标
- const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
- ball.position = localPos;
- }
- // 为额外小球设置碰撞组件
- private setupBallCollider(ball: Node) {
- // 确保有碰撞组件
- let collider = ball.getComponent(CircleCollider2D);
- if (!collider) {
- collider = ball.addComponent(CircleCollider2D);
- }
-
- // 设置碰撞属性(使用配置值)
- collider.radius = this.ballRadius;
- collider.group = this.colliderGroup;
- collider.tag = this.colliderTag;
- collider.sensor = this.sensor;
- collider.friction = this.friction;
- collider.restitution = this.restitution;
-
- // 添加刚体组件
- let rigidBody = ball.getComponent(RigidBody2D);
- if (!rigidBody) {
- rigidBody = ball.addComponent(RigidBody2D);
- }
-
- // 设置刚体属性(使用配置值)
- rigidBody.type = ERigidBody2DType.Dynamic; // 动态刚体
- rigidBody.allowSleep = false;
- rigidBody.gravityScale = this.gravityScale;
- rigidBody.linearDamping = this.linearDamping;
- rigidBody.angularDamping = this.angularDamping;
- rigidBody.fixedRotation = true;
- rigidBody.enabledContactListener = true; // 启用碰撞监听
-
- // 注意:不需要为每个小球单独添加碰撞回调,
- // 因为我们使用的是全局物理系统回调
- }
- // 为额外小球初始化方向和速度
- private initializeBallDirection(ball: Node) {
- // 随机初始方向
- const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
- const direction = new Vec2(Math.cos(angle), Math.sin(angle)).normalize();
-
- // 设置初始速度
- const rigidBody = ball.getComponent(RigidBody2D);
- if (rigidBody) {
- rigidBody.linearVelocity = new Vec2(
- direction.x * this.currentSpeed,
- direction.y * this.currentSpeed
- );
- }
- }
-
-
- // 检查所有已放置方块的碰撞体组件
- private checkBlockColliders() {
-
- if (!this.placedBlocksContainer) {
- return;
- }
-
- if (!this.placedBlocksContainer.isValid) {
- return;
- }
-
- const blocks = [];
- for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
- const block = this.placedBlocksContainer.children[i];
- if (block.name.includes('Block') || block.getChildByName('B1')) {
- blocks.push(block);
- }
- }
-
- let fixedCount = 0;
-
- for (let i = 0; i < blocks.length; i++) {
- const block = blocks[i];
-
- // 检查方块本身的碰撞体
- const blockCollider = block.getComponent(Collider2D);
- if (blockCollider) {
- // 🔧 自动修复碰撞组设置
- if (blockCollider.group !== 2) {
- blockCollider.group = 2; // 设置为Block组
- fixedCount++;
- }
-
- // 确保不是传感器
- if (blockCollider.sensor) {
- blockCollider.sensor = false;
- }
- }
-
- // 检查B1子节点的碰撞体
- const b1Node = block.getChildByName('B1');
- if (b1Node) {
- const b1Collider = b1Node.getComponent(Collider2D);
- if (b1Collider) {
- // 🔧 修复B1子节点的碰撞设置
- if (b1Collider.group !== 2) {
- b1Collider.group = 2; // 设置为Block组
- fixedCount++;
- }
-
- // 确保B1不是传感器(需要实际碰撞)
- if (b1Collider.sensor) {
- b1Collider.sensor = false;
- }
- }
- }
-
- // 检查Weapon子节点
- const weaponNode = this.findWeaponNode(block);
- if (weaponNode) {
- // 武器节点存在
- }
- }
- }
- // 随机位置小球
- positionBallRandomly() {
- if (!this.activeBall) return;
- const transform = this.activeBall.getComponent(UITransform);
- const ballRadius = transform ? transform.width / 2 : this.ballRadius;
-
- // 计算可生成的范围(考虑小球半径,避免生成在边缘)
- const minX = this.gameBounds.left + ballRadius + this.edgeOffset; // 额外偏移,避免生成在边缘
- const maxX = this.gameBounds.right - ballRadius - this.edgeOffset;
- const minY = this.gameBounds.bottom + ballRadius + this.edgeOffset;
- const maxY = this.gameBounds.top - ballRadius - this.edgeOffset;
- // 获取GameArea节点
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- if (!gameArea) {
- return;
- }
-
- // 查找PlacedBlocks节点,它包含所有放置的方块
- if (!this.placedBlocksContainer) {
- this.setRandomPositionDefault(this.activeBall, minX, maxX, minY, maxY);
- return;
- }
-
-
- // 获取所有已放置的方块
- const placedBlocks = [];
- for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
- const block = this.placedBlocksContainer.children[i];
- // 检查是否是方块节点(通常以Block命名或有特定标识)
- if (block.name.includes('Block') || block.getChildByName('B1')) {
- placedBlocks.push(block);
- }
- }
-
- // 如果没有方块,使用默认随机位置
- if (placedBlocks.length === 0) {
- this.setRandomPositionDefault(this.activeBall, minX, maxX, minY, maxY);
- return;
- }
-
- // 尝试找到一个不与任何方块重叠的位置
- let validPosition = false;
- let attempts = 0;
- const maxAttempts = this.maxAttempts; // 从配置中获取最大尝试次数
- let randomX, randomY;
-
- while (!validPosition && attempts < maxAttempts) {
- // 随机生成位置
- randomX = Math.random() * (maxX - minX) + minX;
- randomY = Math.random() * (maxY - minY) + minY;
-
- // 检查是否与任何方块重叠
- let overlapping = false;
- for (const block of placedBlocks) {
- // 获取方块的世界坐标
- const blockWorldPos = block.worldPosition;
-
- // 计算小球与方块的距离
- const distance = Math.sqrt(
- Math.pow(randomX - blockWorldPos.x, 2) +
- Math.pow(randomY - blockWorldPos.y, 2)
- );
-
- // 获取方块的尺寸
- const blockTransform = block.getComponent(UITransform);
- const blockSize = blockTransform ?
- Math.max(blockTransform.width, blockTransform.height) / 2 : this.safeDistance;
-
- // 如果距离小于小球半径+方块尺寸的一半+安全距离,认为重叠
- if (distance < ballRadius + blockSize + this.safeDistance) {
- overlapping = true;
- break;
- }
- }
-
- // 如果没有重叠,找到了有效位置
- if (!overlapping) {
- validPosition = true;
- }
-
- attempts++;
- }
-
- // 如果找不到有效位置,使用默认位置(游戏区域底部中心)
- if (!validPosition) {
- randomX = (this.gameBounds.left + this.gameBounds.right) / 2;
- randomY = this.gameBounds.bottom + ballRadius + this.safeDistance; // 底部上方安全距离单位
- }
-
- // 将世界坐标转换为相对于GameArea的本地坐标
- const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
- this.activeBall.position = localPos;
- }
- // 设置碰撞组件
- setupCollider() {
- if (!this.activeBall) return;
- // 确保小球有刚体组件
- let rigidBody = this.activeBall.getComponent(RigidBody2D);
- if (!rigidBody) {
- rigidBody = this.activeBall.addComponent(RigidBody2D);
- rigidBody.type = ERigidBody2DType.Dynamic; // Dynamic
- rigidBody.gravityScale = this.gravityScale; // 从配置获取重力缩放
- rigidBody.enabledContactListener = true; // 启用碰撞监听
- rigidBody.fixedRotation = true; // 固定旋转
- rigidBody.allowSleep = false; // 不允许休眠
- rigidBody.linearDamping = this.linearDamping; // 从配置获取线性阻尼
- rigidBody.angularDamping = this.angularDamping; // 从配置获取角阻尼
- } else {
- // 确保已有的刚体组件设置正确
- rigidBody.enabledContactListener = true;
- rigidBody.gravityScale = this.gravityScale;
- rigidBody.linearDamping = this.linearDamping; // 从配置获取线性阻尼
- rigidBody.angularDamping = this.angularDamping; // 从配置获取角阻尼
- rigidBody.allowSleep = false; // 不允许休眠
- }
- // 确保小球有碰撞组件
- let collider = this.activeBall.getComponent(CircleCollider2D);
- if (!collider) {
- collider = this.activeBall.addComponent(CircleCollider2D);
- collider.radius = this.radius || this.ballRadius; // 使用已计算的半径或配置值
- collider.tag = this.colliderTag; // 从配置获取小球标签
- collider.group = this.colliderGroup; // 从配置获取碰撞组
- collider.sensor = this.sensor; // 从配置获取传感器设置
- collider.friction = this.friction; // 从配置获取摩擦系数
- collider.restitution = this.restitution; // 从配置获取恢复系数
- } else {
- // 确保已有的碰撞组件设置正确
- collider.sensor = this.sensor;
- collider.restitution = this.restitution;
- collider.group = this.colliderGroup; // 从配置获取碰撞组
- collider.tag = this.colliderTag; // 从配置获取标签
- }
- // === 使用全局回调监听器 ===
- const physics = PhysicsManager.getInstance()?.getSystem();
- if (physics) {
- // 先移除旧监听,避免重复注册
- physics.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
- // 只注册实际需要的碰撞开始事件
- physics.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
- }
- }
- // 碰撞回调 - 处理小球与方块以及小球之间的碰撞
- onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
- // 检查是否为小球之间的碰撞
- if (selfCollider.group === 1 && otherCollider.group === 1) {
- // 小球之间的碰撞 - 防止速度改变
- this.handleBallToBallCollision(selfCollider, otherCollider, contact);
- return;
- }
-
- // 判断哪个是小球,哪个是碰撞对象
- let ballNode: Node = null;
- let otherNode: Node = null;
-
- // 检查self是否为小球(组1)
- if (selfCollider.group === 1) {
- ballNode = selfCollider.node;
- otherNode = otherCollider.node;
- }
- // 检查other是否为小球(组1)
- else if (otherCollider.group === 1) {
- ballNode = otherCollider.node;
- otherNode = selfCollider.node;
- }
-
- // 如果没有找到小球,跳过处理
- if (!ballNode || !otherNode) {
- return;
- }
- // 检查是否为方块碰撞
- const nodeName = otherNode.name;
- const nodePath = this.getNodePath(otherNode);
- // 根据新的预制体结构,检查B1/Weapon路径
- const b1Node = otherNode.getChildByName('B1');
- const hasWeaponChild = b1Node ? b1Node.getChildByName('Weapon') !== null : otherNode.getChildByName('Weapon') !== null;
- const isBlock =
- nodeName.includes('Block') ||
- nodePath.includes('Block') ||
- hasWeaponChild;
- // 如果是方块碰撞,检查防围困机制
- if (isBlock) {
- // 检查方块是否正在被拖拽,如果是则忽略碰撞
- // 需要检查碰撞节点本身或其父节点是否在拖拽列表中
- let isDragging = false;
- let currentNode = otherNode;
-
- // 向上遍历节点树,检查是否有父节点在拖拽列表中
- while (currentNode && !isDragging) {
- if (this.draggingBlocks.has(currentNode)) {
- isDragging = true;
- console.log('[BallController] 发现拖拽方块,忽略碰撞:', currentNode.name, '碰撞节点:', otherNode.name, '路径:', nodePath);
- break;
- }
- currentNode = currentNode.parent;
- }
-
- if (isDragging) {
- console.log('[BallController] 当前拖拽方块数量:', this.draggingBlocks.size);
- if (contact) {
- contact.disabled = true;
- }
- return;
- }
-
- const ballId = ballNode.uuid;
- const currentTime = performance.now() / 1000; // 转换为秒
- // 检查是否处于穿透状态
- const phaseThroughEndTime = this.ballPhaseThrough.get(ballId);
- if (phaseThroughEndTime && currentTime < phaseThroughEndTime) {
- // 处于穿透状态,忽略碰撞但仍播放特效
- const ballAni = BallAni.getInstance();
- if (ballAni) {
- let contactPos: Vec3 = null;
- if (contact && (contact as any).getWorldManifold) {
- const wm = (contact as any).getWorldManifold();
- if (wm && wm.points && wm.points.length > 0) {
- contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
- }
- }
- if (!contactPos) {
- contactPos = otherNode.worldPosition.clone();
- }
- ballAni.playImpactEffect(contactPos);
- }
- // 禁用碰撞
- if (contact) {
- contact.disabled = true;
- }
- return;
- }
- // 记录撞击历史
- if (!this.ballHitHistory.has(ballId)) {
- this.ballHitHistory.set(ballId, []);
- }
- const hitHistory = this.ballHitHistory.get(ballId);
- hitHistory.push(currentTime);
- // 清理过期的撞击记录
- const timeThreshold = currentTime - this.antiTrapTimeWindow;
- while (hitHistory.length > 0 && hitHistory[0] < timeThreshold) {
- hitHistory.shift();
- }
- // 测试模式:显示详细的防围困信息
- // console.log(`[BallController] 测试模式 - 小球撞击统计: 撞击次数=${hitHistory.length}/${this.antiTrapHitThreshold}, 时间窗口=${this.antiTrapTimeWindow}秒, 方块=${otherNode.name}`);
- // 检查是否达到防围困条件
- if (hitHistory.length >= this.antiTrapHitThreshold) {
- //console.log(`[BallController] 测试模式 - 触发防围困机制! 撞击次数已达到阈值 ${this.antiTrapHitThreshold}`);
- // 获取当前偏移尝试次数
- const deflectionAttempts = this.ballDeflectionAttempts.get(ballId) || 0;
-
- if (deflectionAttempts < this.deflectionAttemptThreshold) {
- // 优先使用偏移方式
- this.ballDeflectionAttempts.set(ballId, deflectionAttempts + 1);
- //console.log(`[BallController] 测试模式 - 应用防围困偏移 (第${deflectionAttempts + 1}/${this.deflectionAttemptThreshold}次尝试)`);
-
- // 应用增强偏移反弹
- const rigidBody = ballNode.getComponent(RigidBody2D);
- if (rigidBody && contact) {
- // 获取碰撞法线
- let normal = new Vec2(0, 1);
- if ((contact as any).getWorldManifold) {
- const wm = (contact as any).getWorldManifold();
- if (wm && wm.normal) {
- normal = new Vec2(wm.normal.x, wm.normal.y);
- }
- }
-
- // 计算增强偏移反弹方向
- const currentVelocity = rigidBody.linearVelocity;
- const currentDirection = new Vec2(currentVelocity.x, currentVelocity.y).normalize();
- const oldDirection = `(${currentDirection.x.toFixed(2)}, ${currentDirection.y.toFixed(2)})`;
- const newDirection = this.calculateAntiTrapReflection(currentDirection, normal);
- const newDirectionStr = `(${newDirection.x.toFixed(2)}, ${newDirection.y.toFixed(2)})`;
-
- console.log(`[BallController] 测试模式 - 方向改变: ${oldDirection} -> ${newDirectionStr}`);
-
- // 应用新的速度方向
- const speed = currentVelocity.length();
- rigidBody.linearVelocity = new Vec2(newDirection.x * speed, newDirection.y * speed);
-
- }
-
- // 清空撞击历史,给偏移一个机会
- hitHistory.length = 0;
- } else {
- // 偏移尝试次数已达上限,使用穿透
- console.log(`[BallController] 测试模式 - 偏移尝试已达上限,启用穿透模式 (0.5秒)`);
- this.ballPhaseThrough.set(ballId, currentTime + 0.5);
- // 重置偏移尝试次数
- this.ballDeflectionAttempts.set(ballId, 0);
- // 清空撞击历史
- hitHistory.length = 0;
- // 禁用当前碰撞
- if (contact) {
- contact.disabled = true;
- }
- return;
- }
- }
- }
-
- // 计算碰撞世界坐标
- let contactPos: Vec3 = null;
- if (contact && (contact as any).getWorldManifold) {
- const wm = (contact as any).getWorldManifold();
- if (wm && wm.points && wm.points.length > 0) {
- contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
- }
- }
- if (!contactPos) {
- contactPos = otherNode.worldPosition.clone();
- }
- // 播放撞击特效 - 对所有碰撞都播放特效
- const ballAni = BallAni.getInstance();
- if (ballAni) {
- ballAni.playImpactEffect(contactPos);
- }
-
- if (isBlock) {
- // 播放方块撞击动画
- if (ballAni) {
- ballAni.playBlockHitAnimation(otherNode);
- }
- // 通过事件检查是否可以发射子弹
- const eventBus = EventBus.getInstance();
- let canFire = true;
-
- // 发送检查事件,如果有监听器返回false则不发射
- eventBus.emit(GameEvents.BALL_FIRE_BULLET, { canFire: (value: boolean) => { canFire = value; } });
-
- if (canFire) {
-
- const now = performance.now();
- const lastTime = this.blockFireCooldown.get(otherNode.uuid) || 0;
- if (now - lastTime > this.FIRE_COOLDOWN * 1000) {
- this.blockFireCooldown.set(otherNode.uuid, now);
- this.fireBulletAt(otherNode, contactPos);
- }
- }
- }
- }
- /**
- * 处理小球之间的碰撞 - 保持恒定速度
- */
- private handleBallToBallCollision(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
- const ball1 = selfCollider.node;
- const ball2 = otherCollider.node;
-
- const rigidBody1 = ball1.getComponent(RigidBody2D);
- const rigidBody2 = ball2.getComponent(RigidBody2D);
-
- if (!rigidBody1 || !rigidBody2) {
- return;
- }
-
- // 计算碰撞位置并播放撞击特效
- let contactPos: Vec3 = null;
- if (contact && (contact as any).getWorldManifold) {
- const wm = (contact as any).getWorldManifold();
- if (wm && wm.points && wm.points.length > 0) {
- contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
- }
- }
- if (!contactPos) {
- // 使用两个小球位置的中点作为碰撞位置
- const pos1 = ball1.worldPosition;
- const pos2 = ball2.worldPosition;
- contactPos = new Vec3(
- (pos1.x + pos2.x) / 2,
- (pos1.y + pos2.y) / 2,
- 0
- );
- }
-
- // 播放撞击特效
- const ballAni = BallAni.getInstance();
- if (ballAni) {
- ballAni.playImpactEffect(contactPos);
- }
-
- // 获取碰撞前的速度
- const velocity1 = rigidBody1.linearVelocity.clone();
- const velocity2 = rigidBody2.linearVelocity.clone();
-
- // 计算速度大小
- const speed1 = Math.sqrt(velocity1.x * velocity1.x + velocity1.y * velocity1.y);
- const speed2 = Math.sqrt(velocity2.x * velocity2.x + velocity2.y * velocity2.y);
-
- // 延迟一帧后恢复正确的速度,避免物理引擎的速度改变
- this.scheduleOnce(() => {
- if (ball1.isValid && rigidBody1.isValid) {
- const currentVel1 = rigidBody1.linearVelocity;
- const currentSpeed1 = Math.sqrt(currentVel1.x * currentVel1.x + currentVel1.y * currentVel1.y);
-
- // 如果速度发生了显著变化,恢复到目标速度
- if (Math.abs(currentSpeed1 - this.currentSpeed) > 5) {
- const normalizedVel1 = currentVel1.clone().normalize();
- rigidBody1.linearVelocity = new Vec2(
- normalizedVel1.x * this.currentSpeed,
- normalizedVel1.y * this.currentSpeed
- );
- }
- }
-
- if (ball2.isValid && rigidBody2.isValid) {
- const currentVel2 = rigidBody2.linearVelocity;
- const currentSpeed2 = Math.sqrt(currentVel2.x * currentVel2.x + currentVel2.y * currentVel2.y);
-
- // 如果速度发生了显著变化,恢复到目标速度
- if (Math.abs(currentSpeed2 - this.currentSpeed) > 5) {
- const normalizedVel2 = currentVel2.clone().normalize();
- rigidBody2.linearVelocity = new Vec2(
- normalizedVel2.x * this.currentSpeed,
- normalizedVel2.y * this.currentSpeed
- );
- }
- }
- }, 0.016); // 约一帧的时间
- }
-
- // 计算反射向量
- calculateReflection(direction: Vec2, normal: Vec2): Vec2 {
- // 使用反射公式: R = V - 2(V·N)N
- const dot = direction.x * normal.x + direction.y * normal.y;
- const reflection = new Vec2(
- direction.x - 2 * dot * normal.x,
- direction.y - 2 * dot * normal.y
- );
- reflection.normalize();
-
- // 添加一些随机性,避免重复的反弹路径
- const randomAngle = (Math.random() - 0.5) * this.maxReflectionRandomness; // 随机角度
- const cos = Math.cos(randomAngle);
- const sin = Math.sin(randomAngle);
-
- // 应用随机旋转
- const randomizedReflection = new Vec2(
- reflection.x * cos - reflection.y * sin,
- reflection.x * sin + reflection.y * cos
- );
-
- // 更强的防水平/垂直往复运动机制
- // 增大最小角度阈值,并添加更强的随机偏移
- const minAngleFromAxis = 0.5; // 从0.3增加到0.5,约28.6度
- const strongRandomOffset = 0.2; // 增加随机偏移范围
-
- // 检查是否接近水平方向(y分量过小)
- if (Math.abs(randomizedReflection.y) < minAngleFromAxis) {
- // 调整y分量,使其远离水平方向,并添加更大的随机偏移
- const sign = randomizedReflection.y >= 0 ? 1 : -1;
- randomizedReflection.y = sign * (minAngleFromAxis + Math.random() * strongRandomOffset);
- // 重新归一化
- randomizedReflection.normalize();
- }
-
- // 检查是否接近垂直方向(x分量过小)
- if (Math.abs(randomizedReflection.x) < minAngleFromAxis) {
- // 调整x分量,使其远离垂直方向,并添加更大的随机偏移
- const sign = randomizedReflection.x >= 0 ? 1 : -1;
- randomizedReflection.x = sign * (minAngleFromAxis + Math.random() * strongRandomOffset);
- // 重新归一化
- randomizedReflection.normalize();
- }
-
- // 额外检查:如果仍然太接近轴向,强制添加对角分量
- const finalCheck = 0.4;
- if (Math.abs(randomizedReflection.y) < finalCheck || Math.abs(randomizedReflection.x) < finalCheck) {
- // 强制添加对角分量,确保既有x又有y的显著分量
- const angle = Math.PI / 4 + (Math.random() - 0.5) * Math.PI / 6; // 45度±15度
- const signX = randomizedReflection.x >= 0 ? 1 : -1;
- const signY = randomizedReflection.y >= 0 ? 1 : -1;
- randomizedReflection.x = signX * Math.cos(angle);
- randomizedReflection.y = signY * Math.sin(angle);
- }
-
- randomizedReflection.normalize();
-
- return randomizedReflection;
- }
- /**
- * 计算防围困增强偏移反弹方向
- * @param direction 当前方向
- * @param normal 碰撞法线
- * @returns 增强偏移后的反弹方向
- */
- calculateAntiTrapReflection(direction: Vec2, normal: Vec2): Vec2 {
- // 使用反射公式: R = V - 2(V·N)N
- const dot = direction.x * normal.x + direction.y * normal.y;
- const reflection = new Vec2(
- direction.x - 2 * dot * normal.x,
- direction.y - 2 * dot * normal.y
- );
- reflection.normalize();
-
- // 应用更强的随机偏移来帮助脱困
- const enhancedRandomness = this.maxReflectionRandomness * this.antiTrapDeflectionMultiplier;
- const randomAngle = (Math.random() - 0.5) * enhancedRandomness;
- const cos = Math.cos(randomAngle);
- const sin = Math.sin(randomAngle);
-
- // 应用随机旋转
- const randomizedReflection = new Vec2(
- reflection.x * cos - reflection.y * sin,
- reflection.x * sin + reflection.y * cos
- );
-
- // 更强的轴向偏移避免
- const minAngleFromAxis = 0.3; // 约17度,比普通反弹更大的偏移
-
- // 检查是否接近水平方向
- if (Math.abs(randomizedReflection.y) < minAngleFromAxis) {
- const sign = randomizedReflection.y >= 0 ? 1 : -1;
- randomizedReflection.y = sign * (minAngleFromAxis + Math.random() * 0.2);
- randomizedReflection.normalize();
- }
-
- // 检查是否接近垂直方向
- if (Math.abs(randomizedReflection.x) < minAngleFromAxis) {
- const sign = randomizedReflection.x >= 0 ? 1 : -1;
- randomizedReflection.x = sign * (minAngleFromAxis + Math.random() * 0.2);
- randomizedReflection.normalize();
- }
-
- randomizedReflection.normalize();
- console.log(`Applied anti-trap enhanced deflection with angle: ${randomAngle}`);
-
- return randomizedReflection;
- }
- /**
- * 从方块武器发射子弹攻击敌人 - 重构版本
- * 现在直接创建子弹实例并使用BulletController的实例方法
- * @param blockNode 激活的方块节点
- */
- fireBullet(blockNode: Node) {
- // 检查子弹预制体是否存在
- if (!this.bulletPrefab) {
- return;
- }
-
- // 查找方块中的Weapon节点
- const weaponNode = this.findWeaponNode(blockNode);
- let firePosition: Vec3;
-
- if (!weaponNode) {
- firePosition = blockNode.worldPosition;
- } else {
- // 获取武器的世界坐标作为发射位置
- try {
- firePosition = weaponNode.worldPosition;
- } catch (error) {
- // 备用方案:使用方块坐标
- firePosition = blockNode.worldPosition;
- }
- }
-
- // 通过事件系统发射子弹,这样可以被暂停检查拦截
- EventBus.getInstance().emit(GameEvents.BALL_FIRE_BULLET, blockNode, firePosition);
- }
-
- /**
- * 创建并发射子弹 - 使用新的WeaponBullet系统
- * @param firePosition 发射位置(世界坐标)
- * @param weaponNode 武器节点(包含WeaponInfo组件)
- * @param sourceBlock 发射源方块节点(用于回旋镖返回)
- */
- private createAndFireBullet(firePosition: Vec3, weaponNode: Node | null, sourceBlock?: Node) {
-
- // 确保武器配置加载
- WeaponBullet.loadWeaponsData().then(() => {
- let finalConfig: WeaponConfig | null = null;
-
- // 优先从武器节点的WeaponInfo组件获取配置
- if (weaponNode && weaponNode.isValid) {
- const weaponInfo = weaponNode.getComponent(WeaponInfo);
- if (weaponInfo) {
- finalConfig = weaponInfo.getWeaponConfig();
- console.log(`[BallController] 从武器节点获取武器配置: ${finalConfig?.name || '未知'}`);
-
- // 检查武器是否可以开火
- if (!weaponInfo.canFire()) {
- console.log(`[BallController] 武器 ${finalConfig?.name || '未知'} 冷却中,无法开火`);
- return;
- }
-
- // 记录开火时间
- weaponInfo.recordFireTime();
- }
- }
-
- // 如果没有从武器节点获取到配置,使用默认配置
- if (!finalConfig) {
- const defaultWeaponId = 'pea_shooter';
- finalConfig = WeaponBullet.getWeaponConfig(defaultWeaponId);
- console.log(`[BallController] 使用默认武器配置: ${defaultWeaponId}`);
- }
-
- if (!finalConfig) {
- console.warn(`[BallController] 无法获取武器配置,取消发射`);
- return;
- }
-
- // 获取WeaponInfo组件(如果有的话)
- let weaponInfoComponent: WeaponInfo | null = null;
- if (weaponNode && weaponNode.isValid) {
- weaponInfoComponent = weaponNode.getComponent(WeaponInfo);
- }
-
- // 获取BlockInfo组件(如果有的话)
- // BlockInfo组件位于方块的Node子节点上,而不是Weapon子节点上
- let blockInfoComponent: BlockInfo | null = null;
- if (weaponNode && weaponNode.isValid && weaponNode.parent) {
- // 从weaponNode的父节点(方块根节点)查找Node子节点
- const blockRootNode = weaponNode.parent;
- const nodeChild = blockRootNode.getChildByName('Node');
- if (nodeChild) {
- blockInfoComponent = nodeChild.getComponent(BlockInfo);
- if (blockInfoComponent) {
- console.log(`[BallController] 找到BlockInfo组件,稀有度等级: ${blockInfoComponent.rarity}, 稀有度名称: ${blockInfoComponent.getRarityName()}`);
- } else {
- console.log(`[BallController] Node子节点上未找到BlockInfo组件`);
- }
- } else {
- console.log(`[BallController] 未找到Node子节点`);
- }
-
- // 如果还是没找到,尝试直接从weaponNode上获取(兼容旧结构)
- if (!blockInfoComponent) {
- blockInfoComponent = weaponNode.getComponent(BlockInfo);
- if (blockInfoComponent) {
- console.log(`[BallController] 从weaponNode上找到BlockInfo组件,稀有度等级: ${blockInfoComponent.rarity}, 稀有度名称: ${blockInfoComponent.getRarityName()}`);
- } else {
- console.log(`[BallController] 未找到BlockInfo组件,将使用JSON配置中的稀有度`);
- }
- }
- }
-
- // 创建子弹初始化数据
- const initData: BulletInitData = {
- weaponId: finalConfig.id,
- firePosition: firePosition,
- autoTarget: true,
- weaponConfig: finalConfig,
- weaponInfo: weaponInfoComponent,
- blockInfo: blockInfoComponent,
- sourceBlock: sourceBlock // 传递发射源方块节点
- };
-
- // 验证初始化数据
- if (!WeaponBullet.validateInitData(initData)) {
- console.warn(`[BallController] 子弹初始化数据验证失败`);
- return;
- }
-
- // 查找GameArea(子弹统一添加到此节点)
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- if (!gameArea) {
- console.warn(`[BallController] 未找到GameArea节点,无法发射子弹`);
- return;
- }
- // === 根据武器配置选择合适的预制体 ===
- const trailEffect = finalConfig.bulletConfig?.visual?.trailEffect;
- const needsContainerPrefab = Boolean(trailEffect);
- const prefabToUse: Prefab = (needsContainerPrefab && this.bulletContainerPrefab) ? this.bulletContainerPrefab : this.bulletPrefab;
- if (!prefabToUse) {
- console.warn(`[BallController] 没有可用的子弹预制体`);
- return;
- }
- // 使用批量创建逻辑
- console.log(`[BallController] 开始创建子弹 - 武器: ${finalConfig.name}, 预制体: ${prefabToUse ? prefabToUse.name : 'null'}`);
- const bullets = WeaponBullet.createBullets(initData, prefabToUse as any);
- console.log(`[BallController] WeaponBullet.createBullets 返回了 ${bullets.length} 个子弹`);
-
- bullets.forEach((b, index) => {
- console.log(`[BallController] 添加第 ${index + 1} 个子弹到场景 - 子弹节点: ${b ? b.name : 'null'}, 是否有效: ${b ? b.isValid : 'false'}`);
- if (b && b.isValid) {
- gameArea.addChild(b);
- console.log(`[BallController] 子弹 ${index + 1} 成功添加到场景,世界坐标: ${b.worldPosition}`);
- } else {
- console.error(`[BallController] 子弹 ${index + 1} 无效,无法添加到场景`);
- }
- });
-
- console.log(`[BallController] 成功发射 ${bullets.length} 发子弹,武器: ${finalConfig.name}`);
-
- }).catch(error => {
- console.error(`[BallController] 武器配置加载失败:`, error);
- });
- }
-
- // 递归查找Weapon节点
- private findWeaponNode(node: Node): Node | null {
- // 检查节点是否有效
- if (!node || !node.isValid) {
- console.warn('[BallController] findWeaponNode: 传入的节点无效');
- return null;
- }
-
- // 根据新的预制体结构,武器节点直接位于方块根节点下
- // 首先检查当前节点是否有Weapon子节点
- const weaponNode = node.getChildByName('Weapon');
- if (weaponNode) {
- return weaponNode;
- }
-
- // 如果当前节点没有Weapon子节点,检查父节点(可能传入的是Node子节点而不是预制体根节点)
- if (node.parent) {
- const parentWeaponNode = node.parent.getChildByName('Weapon');
- if (parentWeaponNode) {
- return parentWeaponNode;
- }
- }
-
- // 最后使用递归方式查找(兼容其他可能的结构)
- for (let i = 0; i < node.children.length; i++) {
- const child = node.children[i];
- const foundWeapon = this.findWeaponNode(child);
- if (foundWeapon) {
- return foundWeapon;
- }
- }
-
- // 如果都没找到,返回null
- console.warn('[BallController] 方块', node.name, '中未找到武器节点');
- return null;
- }
- // 获取节点的完整路径
- private getNodePath(node: Node): string {
- let path = node.name;
- let current = node;
-
- while (current.parent) {
- current = current.parent;
- path = current.name + '/' + path;
- }
-
- return path;
- }
- private debugDragCounter = 0;
-
- update(dt: number) {
- // 只有当小球已启动时才执行运动逻辑
- if (!this.ballStarted || !this.initialized) {
- return;
- }
-
- // 维持所有小球的恒定速度
- this.maintainAllBallsSpeed();
-
- // 更新小球运动历史数据(用于检测振荡模式)
- this.updateBallMovementHistory();
-
- // 清理过期的防围困状态
- this.cleanupExpiredAntiTrapStates();
-
- // 定期检查小球位置,防止小球被挤出游戏区域
- this.lastPositionCheckTime += dt;
- if (this.lastPositionCheckTime >= this.positionCheckInterval) {
- this.checkAndRescueAllBalls();
- this.lastPositionCheckTime = 0;
- }
-
- // 定期检查小球是否接近方块但没有触发碰撞(调试用)
- if (this.activeBall && this.activeBall.isValid) {
- this.debugCheckNearBlocks();
- }
-
- // 定期调试拖拽状态(每5秒一次)
- this.debugDragCounter += dt;
- if (this.debugDragCounter >= 5.0 && this.draggingBlocks.size > 0) {
- console.log('[BallController] 定期调试 - 当前拖拽状态:');
- this.debugDraggingBlocks();
- this.debugDragCounter = 0;
- }
- }
-
- /**
- * 更新小球运动历史数据(用于检测振荡模式)
- */
- private updateBallMovementHistory() {
- if (!this.activeBall || !this.activeBall.isValid) {
- return;
- }
- const ballId = this.activeBall.uuid;
- const currentTime = Date.now() / 1000; // 转换为秒
- const currentPos = this.activeBall.getWorldPosition();
- const rigidBody = this.activeBall.getComponent(RigidBody2D);
-
- if (!rigidBody) {
- return;
- }
- const currentVelocity = rigidBody.linearVelocity;
- const currentDirection = new Vec2(currentVelocity.x, currentVelocity.y).normalize();
- // 初始化历史记录
- if (!this.ballPositionHistory.has(ballId)) {
- this.ballPositionHistory.set(ballId, []);
- this.ballDirectionHistory.set(ballId, []);
- this.ballOscillationDetection.set(ballId, {
- lastDirectionChange: currentTime,
- directionChangeCount: 0,
- oscillationAxis: 'none',
- oscillationStartTime: 0
- });
- }
- const posHistory = this.ballPositionHistory.get(ballId);
- const dirHistory = this.ballDirectionHistory.get(ballId);
- const oscillationData = this.ballOscillationDetection.get(ballId);
- // 更新位置历史
- posHistory.push(new Vec2(currentPos.x, currentPos.y));
- if (posHistory.length > this.positionHistorySize) {
- posHistory.shift();
- }
- // 更新方向历史
- dirHistory.push(currentDirection.clone());
- if (dirHistory.length > this.positionHistorySize) {
- dirHistory.shift();
- }
- // 检测方向改变
- if (dirHistory.length >= 2) {
- const prevDirection = dirHistory[dirHistory.length - 2];
- const dotProduct = Vec2.dot(prevDirection, currentDirection);
-
- // 如果方向改变超过90度(点积小于0),认为是显著的方向改变
- if (dotProduct < 0) {
- oscillationData.directionChangeCount++;
- oscillationData.lastDirectionChange = currentTime;
-
- if (this.testMode) {
- //console.log(`[防围困] 小球 ${ballId.substring(0, 8)} 方向改变,累计次数: ${oscillationData.directionChangeCount}`);
- }
- }
- }
- // 检测振荡模式
- this.detectOscillationPattern(ballId, currentTime);
- }
- /**
- * 检测振荡模式
- */
- private detectOscillationPattern(ballId: string, currentTime: number) {
- const oscillationData = this.ballOscillationDetection.get(ballId);
- const posHistory = this.ballPositionHistory.get(ballId);
-
- if (!oscillationData || !posHistory || posHistory.length < 10) {
- return;
- }
- // 检查是否在时间窗口内有足够的方向改变
- const timeSinceLastChange = currentTime - oscillationData.lastDirectionChange;
- if (timeSinceLastChange > this.oscillationTimeWindow) {
- // 重置计数器
- oscillationData.directionChangeCount = 0;
- oscillationData.oscillationAxis = 'none';
- return;
- }
- // 如果方向改变次数超过阈值,分析振荡轴向
- if (oscillationData.directionChangeCount >= this.directionChangeThreshold) {
- const axis = this.analyzeOscillationAxis(posHistory);
-
- if (axis !== 'none' && oscillationData.oscillationAxis === 'none') {
- // 开始振荡检测
- oscillationData.oscillationAxis = axis;
- oscillationData.oscillationStartTime = currentTime;
-
- if (this.testMode) {
- console.log(`[防围困] 检测到小球 ${ballId.substring(0, 8)} 在${axis === 'horizontal' ? '水平' : '垂直'}方向振荡`);
- }
-
- // 触发增强防围困机制
- this.triggerEnhancedAntiTrap(ballId, axis);
- }
- }
- }
- /**
- * 分析振荡轴向
- */
- private analyzeOscillationAxis(posHistory: Vec2[]): 'horizontal' | 'vertical' | 'none' {
- if (posHistory.length < 10) {
- return 'none';
- }
- const recentPositions = posHistory.slice(-10);
- let minX = recentPositions[0].x, maxX = recentPositions[0].x;
- let minY = recentPositions[0].y, maxY = recentPositions[0].y;
- for (const pos of recentPositions) {
- minX = Math.min(minX, pos.x);
- maxX = Math.max(maxX, pos.x);
- minY = Math.min(minY, pos.y);
- maxY = Math.max(maxY, pos.y);
- }
- const xRange = maxX - minX;
- const yRange = maxY - minY;
- // 判断主要运动方向
- if (xRange > this.oscillationDistanceThreshold && yRange < this.oscillationDistanceThreshold / 2) {
- return 'horizontal';
- } else if (yRange > this.oscillationDistanceThreshold && xRange < this.oscillationDistanceThreshold / 2) {
- return 'vertical';
- }
- return 'none';
- }
- /**
- * 触发增强防围困机制
- */
- private triggerEnhancedAntiTrap(ballId: string, oscillationAxis: 'horizontal' | 'vertical') {
- const ball = this.activeBall;
- if (!ball || !ball.isValid || ball.uuid !== ballId) {
- return;
- }
- const rigidBody = ball.getComponent(RigidBody2D);
- if (!rigidBody) {
- return;
- }
- if (this.testMode) {
- console.log(`[防围困] 触发增强防围困机制 - 小球 ${ballId.substring(0, 8)},轴向: ${oscillationAxis}`);
- }
- // 根据振荡轴向应用不同的策略
- if (oscillationAxis === 'horizontal') {
- // 水平振荡:给予垂直方向的随机冲量
- const verticalImpulse = (Math.random() - 0.5) * this.baseSpeed * 0.8;
- const newVelocity = new Vec2(rigidBody.linearVelocity.x * 0.3, verticalImpulse);
- rigidBody.linearVelocity = newVelocity;
-
- if (this.testMode) {
- console.log(`[防围困] 水平振荡处理 - 应用垂直冲量: ${verticalImpulse.toFixed(2)}`);
- }
- } else if (oscillationAxis === 'vertical') {
- // 垂直振荡:给予水平方向的随机冲量
- const horizontalImpulse = (Math.random() - 0.5) * this.baseSpeed * 0.8;
- const newVelocity = new Vec2(horizontalImpulse, rigidBody.linearVelocity.y * 0.3);
- rigidBody.linearVelocity = newVelocity;
-
- if (this.testMode) {
- console.log(`[防围困] 垂直振荡处理 - 应用水平冲量: ${horizontalImpulse.toFixed(2)}`);
- }
- }
- // 重置振荡检测数据
- const oscillationData = this.ballOscillationDetection.get(ballId);
- if (oscillationData) {
- oscillationData.directionChangeCount = 0;
- oscillationData.oscillationAxis = 'none';
- }
- }
- /**
- * 维持所有小球的恒定速度
- */
- private maintainAllBallsSpeed() {
- const balls = this.getAllActiveBalls();
- for (const ball of balls) {
- this.maintainBallSpeed(ball);
- }
- }
-
- /**
- * 维持单个小球的恒定速度
- */
- private maintainBallSpeed(ball: Node) {
- const rigidBody = ball.getComponent(RigidBody2D);
- if (!rigidBody) return;
-
- // 获取当前速度
- const currentVelocity = rigidBody.linearVelocity;
- const speed = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
-
- // 如果速度过低或过高,重新设置速度以维持恒定运动
- if (speed < this.currentSpeed * 0.85 || speed > this.currentSpeed * 1.15) {
- // 保持当前方向,但调整速度大小
- if (speed > 0.1) {
- const normalizedVelocity = currentVelocity.clone().normalize();
- rigidBody.linearVelocity = new Vec2(
- normalizedVelocity.x * this.currentSpeed,
- normalizedVelocity.y * this.currentSpeed
- );
- } else {
- // 如果速度几乎为0,给一个随机方向
- const angle = Math.random() * Math.PI * 2;
- rigidBody.linearVelocity = new Vec2(
- Math.cos(angle) * this.currentSpeed,
- Math.sin(angle) * this.currentSpeed
- );
- }
- }
-
- // 更新主小球的方向向量(用于其他逻辑)
- if (ball === this.activeBall && speed > 1.0) {
- this.direction.x = currentVelocity.x / speed;
- this.direction.y = currentVelocity.y / speed;
- }
- }
-
- // 调试方法:检查小球是否接近方块但没有触发物理碰撞
- private debugCheckCounter = 0;
- private debugCheckNearBlocks() {
- this.debugCheckCounter++;
- // 每60帧(约1秒)检查一次
- if (this.debugCheckCounter % 60 !== 0) return;
-
- const ballPos = this.activeBall.worldPosition;
- if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) return;
-
- let nearestDistance = Infinity;
- let nearestBlock = null;
-
- for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
- const block = this.placedBlocksContainer.children[i];
- if (block.name.includes('Block') || block.getChildByName('B1')) {
- const blockPos = block.worldPosition;
- const distance = Math.sqrt(
- Math.pow(ballPos.x - blockPos.x, 2) +
- Math.pow(ballPos.y - blockPos.y, 2)
- );
-
- if (distance < nearestDistance) {
- nearestDistance = distance;
- nearestBlock = block;
- }
- }
- }
-
- if (nearestBlock && nearestDistance < 100) {
- // 检查小球的碰撞体状态
- const ballCollider = this.activeBall.getComponent(Collider2D);
- if (ballCollider) {
- if (ballCollider instanceof CircleCollider2D) {
- // 小球碰撞半径检查
- }
- }
-
- // 检查小球的刚体状态
- const ballRigidBody = this.activeBall.getComponent(RigidBody2D);
- if (ballRigidBody) {
- // 刚体状态检查
- }
-
- // 检查最近的方块碰撞体
- const blockCollider = nearestBlock.getComponent(Collider2D);
- if (blockCollider) {
- // 方块碰撞体检查
- }
- }
- }
- // 初始化方向
- initializeDirection() {
- // 测试模式:使用完全垂直或水平方向来测试防围困机制
- if (this.testMode) {
- // 四个基本方向:上、下、左、右
- const directions = [
- { x: 0, y: 1 }, // 向上
- { x: 0, y: -1 }, // 向下
- { x: 1, y: 0 }, // 向右
- { x: -1, y: 0 } // 向左
- ];
-
- // 随机选择一个基本方向
- const randomIndex = Math.floor(Math.random() * directions.length);
- const selectedDirection = directions[randomIndex];
-
- this.direction.x = selectedDirection.x;
- this.direction.y = selectedDirection.y;
- this.direction.normalize();
-
- console.log(`[BallController] 测试模式 - 小球初始方向: ${randomIndex === 0 ? '向上' : randomIndex === 1 ? '向下' : randomIndex === 2 ? '向右' : '向左'}`);
- } else {
- // 原始随机方向模式
- const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
- this.direction.x = Math.cos(angle);
- this.direction.y = Math.sin(angle);
- this.direction.normalize();
- }
-
- // 设置初始速度
- if (this.activeBall) {
- const rigidBody = this.activeBall.getComponent(RigidBody2D);
- if (rigidBody) {
- rigidBody.linearVelocity = new Vec2(
- this.direction.x * this.currentSpeed,
- this.direction.y * this.currentSpeed
- );
- }
- }
- }
- // 初始化球的参数 - 公开方法,供GameManager调用
- public initialize() {
- this.calculateGameBounds();
- this.createBall();
-
- // 检查方块碰撞体(延迟执行,确保方块已放置)
- this.scheduleOnce(() => {
- this.checkBlockColliders();
- }, 0.5);
- }
-
- // 启动小球 - 公开方法,在确定按钮点击后调用
- public startBall() {
- // 检查ballPrefab是否设置
- if (!this.ballPrefab) {
- console.error('[BallController] ballPrefab 未设置,无法创建小球');
- return;
- }
-
- // 如果还没有初始化,先初始化
- if (!this.initialized) {
- this.initialize();
- }
-
- // 确保小球存在且有效
- if (!this.activeBall || !this.activeBall.isValid) {
- this.createBall();
- }
-
- // 检查小球是否成功创建
- if (!this.activeBall) {
- console.error('[BallController] 小球创建失败');
- return;
- }
-
- // 重新定位小球,避免与方块重叠
- this.positionBallRandomly();
-
- // 确保物理组件设置正确
- this.setupCollider();
-
- // 初始化运动方向并开始运动
- this.initializeDirection();
-
- // 设置运动状态
- this.ballStarted = true;
-
- console.log('[BallController] 小球启动完成');
- }
- /**
- * 暂停小球运动:记录当前速度并停止刚体
- */
- public pauseBall() {
- if (this.isPaused) return;
- this.isPaused = true;
- this.ballStarted = false;
- if (this.activeBall && this.activeBall.isValid) {
- const rb = this.activeBall.getComponent(RigidBody2D);
- if (rb) {
- this.pausedVelocity = rb.linearVelocity.clone();
- rb.linearVelocity = new Vec2(0, 0);
- rb.sleep();
- }
- }
- }
- /**
- * 恢复小球运动:恢复暂停前的速度
- */
- public resumeBall() {
- if (!this.isPaused) return;
- this.isPaused = false;
- this.ballStarted = true;
- console.log('恢复小球运动');
- if (this.activeBall && this.activeBall.isValid) {
- const rb = this.activeBall.getComponent(RigidBody2D);
- if (rb) {
- rb.wakeUp();
- const hasPrevVelocity = this.pausedVelocity && (this.pausedVelocity.x !== 0 || this.pausedVelocity.y !== 0);
- if (hasPrevVelocity) {
- rb.linearVelocity = this.pausedVelocity.clone();
- } else {
- // 若没有记录速度,则重新初始化方向
- this.initializeDirection();
- }
- }
- }
- }
- /**
- * 暂停所有小球运动:记录当前速度并停止所有刚体
- */
- public pauseAllBalls() {
- if (this.isPaused) return;
- this.isPaused = true;
- this.ballStarted = false;
- // 清空之前的暂停速度记录
- this.allBallsPausedVelocities.clear();
- // 暂停所有活跃小球(包括主球和任何复制/新增的小球)
- const balls = this.getAllActiveBalls();
- for (const ball of balls) {
- const rb = ball.getComponent(RigidBody2D);
- if (rb) {
- this.allBallsPausedVelocities.set(ball, rb.linearVelocity.clone());
- rb.linearVelocity = new Vec2(0, 0);
- rb.sleep();
- }
- }
- console.log(`[BallController] 已暂停 ${this.allBallsPausedVelocities.size} 个小球`);
- }
- /**
- * 恢复所有小球运动:恢复暂停前的速度
- */
- public resumeAllBalls() {
- if (!this.isPaused) return;
- this.isPaused = false;
- this.ballStarted = true;
-
- console.log(`[BallController] 恢复 ${this.allBallsPausedVelocities.size} 个小球运动`);
-
- // 恢复所有记录的小球
- for (const [ball, velocity] of this.allBallsPausedVelocities) {
- if (ball && ball.isValid) {
- const rb = ball.getComponent(RigidBody2D);
- if (rb) {
- rb.wakeUp();
- const hasVelocity = velocity && (velocity.x !== 0 || velocity.y !== 0);
- if (hasVelocity) {
- rb.linearVelocity = velocity.clone();
- } else {
- // 如果没有记录速度,给一个默认方向
- if (ball === this.activeBall) {
- this.initializeDirection();
- } else {
- // 额外球给一个随机方向
- const angle = Math.random() * Math.PI * 2;
- const speed = this.currentSpeed;
- rb.linearVelocity = new Vec2(Math.cos(angle) * speed, Math.sin(angle) * speed);
- }
- }
- }
- }
- }
-
- // 清空暂停速度记录
- this.allBallsPausedVelocities.clear();
- }
- /**
- * 从给定世界坐标发射子弹
- */
- private fireBulletAt(blockNode: Node, fireWorldPos: Vec3) {
- // 检查方块节点是否有效
- if (!blockNode || !blockNode.isValid) {
- return;
- }
-
- // 检查子弹预制体是否存在
- if (!this.bulletPrefab) {
- console.warn(`[BallController] 子弹预制体未设置,无法发射`);
- return;
- }
-
- // 查找方块中的武器节点
- const weaponNode = this.findWeaponNode(blockNode);
- if (!weaponNode) {
- const blockName = blockNode && blockNode.isValid ? blockNode.name : 'unknown';
- console.warn(`[BallController] 方块 ${blockName} 中未找到武器节点`);
- }
-
- // 传递武器节点和方块节点给createAndFireBullet方法
- this.createAndFireBullet(fireWorldPos, weaponNode, blockNode);
- }
- /**
- * 重置球控制器状态 - 游戏重置时调用
- */
- public resetBallController() {
- console.log('[BallController] 重置球控制器状态');
-
- // 停止球的运动
- this.ballStarted = false;
- this.isPaused = false;
-
- // 清理暂停状态
- this.pausedVelocity = new Vec2();
- this.allBallsPausedVelocities.clear();
-
- // 销毁当前活动的球
- if (this.activeBall && this.activeBall.isValid) {
- console.log('[BallController] 销毁当前活动的球');
- this.activeBall.destroy();
- }
- this.activeBall = null;
-
- // 销毁所有额外创建的球
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- if (gameArea) {
- const additionalBalls = gameArea.children.filter(child =>
- child.name === 'AdditionalBall' && child.isValid
- );
-
- for (const ball of additionalBalls) {
- console.log('[BallController] 销毁额外球:', ball.name);
- ball.destroy();
- }
-
- if (additionalBalls.length > 0) {
- console.log(`[BallController] 已清理 ${additionalBalls.length} 个额外球`);
- }
- }
-
- // 重置初始化状态
- this.initialized = false;
-
- // 清理冷却时间
- this.blockFireCooldown.clear();
-
- // 清理防围困状态数据
- this.ballHitHistory.clear();
- this.ballPhaseThrough.clear();
- this.ballDeflectionAttempts.clear();
-
- // 清理增强防围困机制的历史数据
- this.ballPositionHistory.clear();
- this.ballDirectionHistory.clear();
- this.ballOscillationDetection.clear();
-
- // 清理拖拽方块集合
- this.draggingBlocks.clear();
-
- // 重置球速
- this.updateBallSpeed();
-
- console.log('[BallController] 球控制器重置完成');
- }
- /**
- * 清理过期的防围困状态
- */
- private cleanupExpiredAntiTrapStates() {
- const currentTime = performance.now() / 1000;
-
- // 清理过期的穿透状态
- for (const [ballId, endTime] of this.ballPhaseThrough.entries()) {
- if (currentTime >= endTime) {
- this.ballPhaseThrough.delete(ballId);
- }
- }
-
- // 检查并重置长时间未频繁撞击的球的偏移尝试次数
- for (const [ballId, hitHistory] of this.ballHitHistory.entries()) {
- // 如果撞击历史为空或最近一次撞击超过时间窗口的一半,重置偏移尝试次数
- if (hitHistory.length === 0 ||
- (hitHistory.length > 0 && currentTime - hitHistory[hitHistory.length - 1] > this.antiTrapTimeWindow / 2)) {
- if (this.ballDeflectionAttempts.has(ballId)) {
- this.ballDeflectionAttempts.set(ballId, 0);
- }
- }
- }
- }
-
- /**
- * 清理单个小球的防围困状态数据
- * @param ballId 小球的唯一标识符
- */
- public cleanupBallAntiTrapState(ballId: string) {
- this.ballHitHistory.delete(ballId);
- this.ballPhaseThrough.delete(ballId);
- this.ballDeflectionAttempts.delete(ballId);
- console.log(`Cleaned up anti-trap state for ball ${ballId}`);
- }
- onDestroy() {
- // 清理事件监听
- const eventBus = EventBus.getInstance();
- eventBus.off(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
- eventBus.off(GameEvents.GAME_PAUSE_SKILL_SELECTION, this.onGamePauseSkillSelectionEvent, this);
- eventBus.off(GameEvents.GAME_PAUSE_BLOCK_SELECTION, this.onGamePauseBlockSelectionEvent, this);
- eventBus.off(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
- eventBus.off(GameEvents.RESET_BALL_CONTROLLER, this.onResetBallControllerEvent, this);
- eventBus.off(GameEvents.BALL_CREATE, this.onBallCreateEvent, this);
- eventBus.off(GameEvents.BALL_START, this.onBallStartEvent, this);
- eventBus.off(GameEvents.BALL_CREATE_ADDITIONAL, this.onBallCreateAdditionalEvent, this);
- eventBus.off(GameEvents.BALL_FIRE_BULLET, this.onBallFireBulletEvent, this);
- eventBus.off(GameEvents.BLOCK_DRAG_START, this.onBlockDragStartEvent, this);
- eventBus.off(GameEvents.BLOCK_DRAG_END, this.onBlockDragEndEvent, this);
-
- // 清理物理事件监听器
- const physics = PhysicsManager.getInstance()?.getSystem();
- if (physics) {
- physics.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
- }
-
- // 清理防围困状态数据
- this.ballHitHistory.clear();
- this.ballPhaseThrough.clear();
- this.ballDeflectionAttempts.clear();
- }
- private updateBallSpeed() {
- const skillManager = PersistentSkillManager.getInstance();
- if (skillManager) {
- this.currentSpeed = skillManager.applyBallSpeedBonus(this.baseSpeed);
- } else {
- this.currentSpeed = this.baseSpeed;
- }
- }
- // ==================== 小球位置检查机制 ====================
-
- /**
- * 获取所有活跃的小球
- * @returns 返回所有活跃小球的数组
- */
- private getAllActiveBalls(): Node[] {
- const balls: Node[] = [];
- const gameArea = find('Canvas/GameLevelUI/GameArea');
-
- // 主球优先加入
- if (this.activeBall && this.activeBall.isValid) {
- balls.push(this.activeBall);
- }
-
- // 包含所有处于球碰撞分组的节点(不依赖名称),避免遗漏复制出的主球
- if (gameArea) {
- for (const child of gameArea.children) {
- if (!child.isValid) continue;
- if (child === this.activeBall) continue;
- const collider = child.getComponent(CircleCollider2D);
- if (collider && collider.group === this.colliderGroup) {
- balls.push(child);
- }
- }
- }
- return balls;
- }
-
- /**
- * 检查单个小球是否在游戏区域内
- * @param ball 要检查的小球节点
- * @returns 如果小球在游戏区域内返回true,否则返回false
- */
- private checkBallPosition(ball: Node): boolean {
- if (!ball || !ball.isValid) {
- return false;
- }
-
- // 获取小球的世界坐标
- const worldPos = ball.getWorldPosition();
-
- // 计算扩展后的边界(比游戏区域稍大,避免误判)
- const extension = this.positionCheckBoundaryExtension;
- const extendedBounds = {
- left: this.gameBounds.left - extension,
- right: this.gameBounds.right + extension,
- top: this.gameBounds.top + extension,
- bottom: this.gameBounds.bottom - extension
- };
-
- // 检查小球是否在扩展边界内
- const isInBounds = worldPos.x >= extendedBounds.left &&
- worldPos.x <= extendedBounds.right &&
- worldPos.y >= extendedBounds.bottom &&
- worldPos.y <= extendedBounds.top;
-
- if (!isInBounds) {
- console.warn(`[BallController] 小球 ${ball.name} 超出游戏区域:`, {
- position: { x: worldPos.x, y: worldPos.y },
- bounds: extendedBounds
- });
- }
-
- return isInBounds;
- }
-
- /**
- * 将小球重置回游戏区域
- * @param ball 要重置的小球节点
- */
- private rescueBallToGameArea(ball: Node): void {
- if (!ball || !ball.isValid) {
- return;
- }
-
- console.log(`[BallController] 正在找回小球 ${ball.name}`);
-
- // 使用与小球生成相同的安全位置设置逻辑
- this.positionBallSafely(ball);
-
- // 重新设置小球的运动方向和速度
- const rigidBody = ball.getComponent(RigidBody2D);
- if (rigidBody) {
- // 随机新的运动方向
- const angle = Math.random() * Math.PI * 2;
- const direction = new Vec2(Math.cos(angle), Math.sin(angle)).normalize();
-
- // 设置新的速度
- rigidBody.linearVelocity = new Vec2(
- direction.x * this.currentSpeed,
- direction.y * this.currentSpeed
- );
- }
-
- console.log(`[BallController] 小球 ${ball.name} 已重置到安全位置`);
- }
-
- /**
- * 为小球设置安全位置(复用生成位置逻辑)
- * @param ball 要设置位置的小球节点
- */
- private positionBallSafely(ball: Node): void {
- if (!ball) return;
- const transform = ball.getComponent(UITransform);
- const ballRadius = transform ? transform.width / 2 : this.ballRadius;
-
- // 计算可生成的范围(考虑小球半径,避免生成在边缘)
- const minX = this.gameBounds.left + ballRadius + this.edgeOffset;
- const maxX = this.gameBounds.right - ballRadius - this.edgeOffset;
- const minY = this.gameBounds.bottom + ballRadius + this.edgeOffset;
- const maxY = this.gameBounds.top - ballRadius - this.edgeOffset;
- // 获取GameArea节点
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- if (!gameArea) {
- return;
- }
-
- // 查找PlacedBlocks节点,它包含所有放置的方块
- if (!this.placedBlocksContainer) {
- this.setRandomPositionDefault(ball, minX, maxX, minY, maxY);
- return;
- }
-
- if (!this.placedBlocksContainer.isValid) {
- this.setRandomPositionDefault(ball, minX, maxX, minY, maxY);
- return;
- }
-
- // 获取所有已放置的方块
- const placedBlocks = [];
- for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
- const block = this.placedBlocksContainer.children[i];
- // 检查是否是方块节点(通常以Block命名或有特定标识)
- if (block.name.includes('Block') || block.getChildByName('B1')) {
- placedBlocks.push(block);
- }
- }
-
- // 如果没有方块,使用默认随机位置
- if (placedBlocks.length === 0) {
- this.setRandomPositionDefault(ball, minX, maxX, minY, maxY);
- return;
- }
-
- // 尝试找到一个不与任何方块重叠的位置
- let validPosition = false;
- let attempts = 0;
- const maxAttempts = this.maxAttempts;
- let randomX, randomY;
-
- while (!validPosition && attempts < maxAttempts) {
- // 随机生成位置
- randomX = Math.random() * (maxX - minX) + minX;
- randomY = Math.random() * (maxY - minY) + minY;
-
- // 检查是否与任何方块重叠
- let overlapping = false;
- for (const block of placedBlocks) {
- // 获取方块的世界坐标
- const blockWorldPos = block.worldPosition;
-
- // 计算小球与方块的距离
- const distance = Math.sqrt(
- Math.pow(randomX - blockWorldPos.x, 2) +
- Math.pow(randomY - blockWorldPos.y, 2)
- );
-
- // 获取方块的尺寸
- const blockTransform = block.getComponent(UITransform);
- const blockSize = blockTransform ?
- Math.max(blockTransform.width, blockTransform.height) / 2 : this.safeDistance;
-
- // 如果距离小于小球半径+方块尺寸的一半+安全距离,认为重叠
- if (distance < ballRadius + blockSize + this.safeDistance) {
- overlapping = true;
- break;
- }
- }
-
- // 如果没有重叠,找到了有效位置
- if (!overlapping) {
- validPosition = true;
- }
-
- attempts++;
- }
-
- // 如果找不到有效位置,使用默认位置(游戏区域底部中心)
- if (!validPosition) {
- randomX = (this.gameBounds.left + this.gameBounds.right) / 2;
- randomY = this.gameBounds.bottom + ballRadius + this.safeDistance;
- }
-
- // 将世界坐标转换为相对于GameArea的本地坐标
- const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
- ball.position = localPos;
- }
-
- /**
- * 设置小球默认位置
- * @param ball 小球节点
- * @param minX 最小X坐标
- * @param maxX 最大X坐标
- * @param minY 最小Y坐标
- * @param maxY 最大Y坐标
- */
- private setRandomPositionDefault(ball: Node, minX: number, maxX: number, minY: number, maxY: number): void {
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- if (!gameArea) return;
-
- // 随机生成位置
- const randomX = Math.random() * (maxX - minX) + minX;
- const randomY = Math.random() * (maxY - minY) + minY;
-
- // 将世界坐标转换为相对于GameArea的本地坐标
- const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
- ball.position = localPos;
- }
-
- /**
- * 检查并找回所有超出游戏区域的小球
- */
- private checkAndRescueAllBalls(): void {
- if (!this.enableBallPositionCheck) {
- return;
- }
-
- const balls = this.getAllActiveBalls();
- let rescuedCount = 0;
-
- balls.forEach(ball => {
- if (!this.checkBallPosition(ball)) {
- this.rescueBallToGameArea(ball);
- rescuedCount++;
- }
- });
-
- if (rescuedCount > 0) {
- console.log(`[BallController] 本次检查找回了 ${rescuedCount} 个小球`);
- }
- }
- }
|