BallController.ts 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432
  1. import { _decorator, Component, Node, Vec2, Vec3, UITransform, Collider2D, Contact2DType, IPhysics2DContact, RigidBody2D, Prefab, instantiate, find, CircleCollider2D, JsonAsset, ERigidBody2DType } from 'cc';
  2. import { PhysicsManager } from '../Core/PhysicsManager';
  3. import { WeaponBullet, BulletInitData } from './WeaponBullet';
  4. import { WeaponConfig } from '../Core/ConfigManager';
  5. import EventBus, { GameEvents } from '../Core/EventBus';
  6. import { PersistentSkillManager } from '../FourUI/SkillSystem/PersistentSkillManager';
  7. import { BallControllerConfig } from '../Core/ConfigManager';
  8. import { WeaponInfo } from './BlockSelection/WeaponInfo';
  9. import { BlockInfo } from './BlockSelection/BlockInfo';
  10. import { BallAni } from '../Animations/BallAni';
  11. import { JsonConfigLoader } from '../Core/JsonConfigLoader';
  12. const { ccclass, property } = _decorator;
  13. @ccclass('BallController')
  14. export class BallController extends Component {
  15. // 球的预制体
  16. @property({
  17. type: Prefab,
  18. tooltip: '拖拽Ball预制体到这里'
  19. })
  20. public ballPrefab: Prefab = null;
  21. // 已放置方块容器节点
  22. @property({
  23. type: Node,
  24. tooltip: '拖拽PlacedBlocks节点到这里(Canvas/GameLevelUI/GameArea/PlacedBlocks)'
  25. })
  26. public placedBlocksContainer: Node = null;
  27. // 球控制器配置文件
  28. // @property({
  29. // type: JsonAsset,
  30. // tooltip: '拖拽ballController.json配置文件到这里'
  31. // })
  32. // public ballControllerConfig: JsonAsset = null; // 已改为动态加载
  33. // 球的移动速度(从配置文件加载)
  34. public baseSpeed: number = 60;
  35. public currentSpeed: number = 60;
  36. // 反弹随机偏移最大角度(弧度)(从配置文件加载)
  37. public maxReflectionRandomness: number = 0.2;
  38. // 当前活动的球
  39. private activeBall: Node = null;
  40. // 球的方向向量
  41. private direction: Vec2 = new Vec2();
  42. // GameArea区域边界
  43. private gameBounds = {
  44. left: 0,
  45. right: 0,
  46. top: 0,
  47. bottom: 0
  48. };
  49. // 球的半径
  50. private radius: number = 0;
  51. // 配置数据
  52. private config: BallControllerConfig = null;
  53. // 是否已初始化
  54. private initialized: boolean = false;
  55. // 子弹预制体
  56. @property({
  57. type: Prefab,
  58. tooltip: '拖拽子弹预制体到这里'
  59. })
  60. public bulletPrefab: Prefab = null;
  61. // 小球是否已开始运动
  62. private ballStarted: boolean = false;
  63. // 小球暂停时记录的速度
  64. private pausedVelocity: Vec2 = new Vec2();
  65. // 所有小球暂停时记录的速度(包括主球和额外球)
  66. private allBallsPausedVelocities: Map<Node, Vec2> = new Map();
  67. // 标记是否处于暂停状态
  68. private isPaused: boolean = false;
  69. // 在类字段区添加
  70. private blockFireCooldown: Map<string, number> = new Map();
  71. private FIRE_COOLDOWN = 0.05;
  72. // 防围困机制配置(从配置文件加载)
  73. public antiTrapTimeWindow: number = 5.0;
  74. public antiTrapHitThreshold: number = 5;
  75. public deflectionAttemptThreshold: number = 3;
  76. public antiTrapDeflectionMultiplier: number = 3.0;
  77. // 增强防围困机制配置
  78. @property({
  79. tooltip: '振荡检测时间窗口(秒):检测小球往复运动的时间范围'
  80. })
  81. public oscillationTimeWindow: number = 3.0;
  82. @property({
  83. tooltip: '方向改变阈值:触发振荡检测的方向改变次数'
  84. })
  85. public directionChangeThreshold: number = 4;
  86. @property({
  87. tooltip: '位置历史记录数量:用于检测往复运动的位置样本数'
  88. })
  89. public positionHistorySize: number = 20;
  90. @property({
  91. tooltip: '振荡距离阈值:判定为往复运动的最小距离范围'
  92. })
  93. public oscillationDistanceThreshold: number = 100;
  94. // 测试模式开关
  95. @property({
  96. tooltip: '启用测试模式:小球只会向上/下/左/右四个基本方向移动,便于测试防围困机制'
  97. })
  98. public testMode: boolean = true;
  99. // 小球位置检查配置
  100. @property({
  101. tooltip: '启用小球位置检查:定期检查小球是否在游戏区域内,如果不在则找回'
  102. })
  103. public enableBallPositionCheck: boolean = true;
  104. @property({
  105. tooltip: '位置检查间隔(秒):多久检查一次小球位置'
  106. })
  107. public positionCheckInterval: number = 2.0;
  108. @property({
  109. tooltip: '位置检查边界扩展(像素):检查边界比游戏区域稍大,避免误判'
  110. })
  111. public positionCheckBoundaryExtension: number = 50;
  112. // 防围困机制状态
  113. private ballHitHistory: Map<string, number[]> = new Map(); // 记录每个球的撞击时间历史
  114. private ballPhaseThrough: Map<string, number> = new Map(); // 记录每个球的穿透结束时间
  115. private ballDeflectionAttempts: Map<string, number> = new Map(); // 记录每个球的偏移尝试次数
  116. // 增强防围困机制:运动模式检测
  117. private ballPositionHistory: Map<string, Vec2[]> = new Map(); // 记录小球位置历史
  118. private ballDirectionHistory: Map<string, Vec2[]> = new Map(); // 记录小球方向历史
  119. private ballOscillationDetection: Map<string, {
  120. lastDirectionChange: number,
  121. directionChangeCount: number,
  122. oscillationAxis: 'horizontal' | 'vertical' | 'none',
  123. oscillationStartTime: number
  124. }> = new Map(); // 振荡检测数据
  125. // 带尾部特效的子弹容器预制体
  126. @property({
  127. type: Prefab,
  128. tooltip: '拖拽带尾部特效的子弹容器预制体到这里(例如 PelletContainer)'
  129. })
  130. public bulletContainerPrefab: Prefab = null;
  131. // 正在被拖拽的方块集合
  132. private draggingBlocks: Set<Node> = new Set();
  133. // 小球位置检查相关变量
  134. private lastPositionCheckTime: number = 0; // 上次位置检查的时间
  135. async start() {
  136. // 如果没有指定placedBlocksContainer,尝试找到它
  137. if (!this.placedBlocksContainer) {
  138. this.placedBlocksContainer = find('Canvas/GameLevelUI/GameArea/PlacedBlocks');
  139. if (!this.placedBlocksContainer) {
  140. // 找不到PlacedBlocks节点,某些功能可能无法正常工作
  141. }
  142. }
  143. // 加载配置
  144. await this.loadConfig();
  145. // 只进行初始设置,不创建小球
  146. this.calculateGameBounds();
  147. // 监听游戏事件
  148. this.setupEventListeners();
  149. // 监听球速技能变化并更新球速
  150. this.updateBallSpeed();
  151. }
  152. /**
  153. * 设置事件监听器
  154. */
  155. // 加载配置
  156. private async loadConfig(): Promise<void> {
  157. try {
  158. this.config = await JsonConfigLoader.getInstance().loadConfig('ballController') as BallControllerConfig;
  159. this.applyConfig();
  160. console.log('[BallController] ✅ 配置文件通过JsonConfigLoader加载成功:', this.config);
  161. } catch (error) {
  162. console.error('[BallController] 加载配置文件失败:', error);
  163. this.useDefaultConfig();
  164. }
  165. }
  166. private useDefaultConfig(): void {
  167. // 使用默认配置
  168. this.config = {
  169. baseSpeed: 60,
  170. maxReflectionRandomness: 0.2,
  171. antiTrapTimeWindow: 5.0,
  172. antiTrapHitThreshold: 5,
  173. deflectionAttemptThreshold: 3,
  174. antiTrapDeflectionMultiplier: 3.0,
  175. FIRE_COOLDOWN: 0.05,
  176. ballRadius: 10,
  177. gravityScale: 0,
  178. linearDamping: 0,
  179. angularDamping: 0,
  180. colliderGroup: 1,
  181. colliderTag: 1,
  182. friction: 0,
  183. restitution: 1,
  184. safeDistance: 50,
  185. edgeOffset: 20,
  186. sensor: false,
  187. maxAttempts: 50
  188. };
  189. this.applyConfig();
  190. }
  191. // 应用配置
  192. private applyConfig() {
  193. if (!this.config) return;
  194. this.baseSpeed = this.config.baseSpeed;
  195. this.currentSpeed = this.config.baseSpeed;
  196. this.maxReflectionRandomness = this.config.maxReflectionRandomness;
  197. this.antiTrapTimeWindow = this.config.antiTrapTimeWindow;
  198. this.antiTrapHitThreshold = this.config.antiTrapHitThreshold;
  199. this.deflectionAttemptThreshold = this.config.deflectionAttemptThreshold;
  200. this.antiTrapDeflectionMultiplier = this.config.antiTrapDeflectionMultiplier;
  201. this.FIRE_COOLDOWN = this.config.FIRE_COOLDOWN;
  202. console.log('BallController配置已应用:', this.config);
  203. }
  204. // 从配置中获取参数值的辅助方法
  205. private getConfigValue<T>(key: keyof BallControllerConfig, defaultValue: T): T {
  206. return this.config && this.config[key] !== undefined ? this.config[key] as T : defaultValue;
  207. }
  208. // 配置参数的getter方法
  209. private get ballRadius(): number {
  210. return this.getConfigValue('ballRadius', 10);
  211. }
  212. private get gravityScale(): number {
  213. return this.getConfigValue('gravityScale', 0);
  214. }
  215. private get linearDamping(): number {
  216. return this.getConfigValue('linearDamping', 0);
  217. }
  218. private get angularDamping(): number {
  219. return this.getConfigValue('angularDamping', 0);
  220. }
  221. private get colliderGroup(): number {
  222. return this.getConfigValue('colliderGroup', 2);
  223. }
  224. private get colliderTag(): number {
  225. return this.getConfigValue('colliderTag', 1);
  226. }
  227. private get friction(): number {
  228. return this.getConfigValue('friction', 0);
  229. }
  230. private get restitution(): number {
  231. return this.getConfigValue('restitution', 1);
  232. }
  233. private get safeDistance(): number {
  234. return this.getConfigValue('safeDistance', 50);
  235. }
  236. private get edgeOffset(): number {
  237. return this.getConfigValue('edgeOffset', 20);
  238. }
  239. private get sensor(): boolean {
  240. return this.getConfigValue('sensor', false);
  241. }
  242. private get maxAttempts(): number {
  243. return this.getConfigValue('maxAttempts', 50);
  244. }
  245. private setupEventListeners() {
  246. const eventBus = EventBus.getInstance();
  247. // 监听暂停事件
  248. eventBus.on(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
  249. eventBus.on(GameEvents.GAME_PAUSE_SKILL_SELECTION, this.onGamePauseSkillSelectionEvent, this);
  250. eventBus.on(GameEvents.GAME_PAUSE_BLOCK_SELECTION, this.onGamePauseBlockSelectionEvent, this);
  251. // 监听恢复事件
  252. eventBus.on(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  253. eventBus.on(GameEvents.GAME_RESUME_SKILL_SELECTION, this.onGameResumeSkillSelectionEvent, this);
  254. eventBus.on(GameEvents.GAME_RESUME_BLOCK_SELECTION, this.onGameResumeBlockSelectionEvent, this);
  255. // 监听重置球控制器事件
  256. eventBus.on(GameEvents.RESET_BALL_CONTROLLER, this.onResetBallControllerEvent, this);
  257. // 监听球创建事件
  258. eventBus.on(GameEvents.BALL_CREATE, this.onBallCreateEvent, this);
  259. // 监听球启动事件
  260. eventBus.on(GameEvents.BALL_START, this.onBallStartEvent, this);
  261. // 监听创建额外球事件
  262. eventBus.on(GameEvents.BALL_CREATE_ADDITIONAL, this.onBallCreateAdditionalEvent, this);
  263. // 监听子弹发射检查事件
  264. eventBus.on(GameEvents.BALL_FIRE_BULLET, this.onBallFireBulletEvent, this);
  265. // 监听方块拖拽开始事件
  266. eventBus.on(GameEvents.BLOCK_DRAG_START, this.onBlockDragStartEvent, this);
  267. // 监听方块拖拽结束事件
  268. eventBus.on(GameEvents.BLOCK_DRAG_END, this.onBlockDragEndEvent, this);
  269. }
  270. /**
  271. * 处理游戏暂停事件
  272. */
  273. private onGamePauseEvent() {
  274. console.log('[BallController] 接收到游戏暂停事件,暂停小球运动');
  275. this.pauseBall();
  276. }
  277. /**
  278. * 处理技能选择暂停事件(所有小球完全停止)
  279. */
  280. private onGamePauseSkillSelectionEvent() {
  281. console.log('[BallController] 接收到技能选择暂停事件,暂停所有小球运动');
  282. this.pauseAllBalls();
  283. }
  284. /**
  285. * 处理底板选择暂停事件(所有小球继续运动)
  286. */
  287. private onGamePauseBlockSelectionEvent() {
  288. console.log('[BallController] 接收到底板选择暂停事件,小球继续运动');
  289. // 底板选择时不暂停小球运动,只是标记游戏状态为暂停
  290. this.isPaused = true;
  291. }
  292. /**
  293. * 处理游戏恢复事件
  294. */
  295. private onGameResumeEvent() {
  296. console.log('[BallController] 接收到游戏恢复事件,恢复小球运动');
  297. this.resumeAllBalls();
  298. }
  299. /**
  300. * 处理技能选择恢复事件
  301. */
  302. private onGameResumeSkillSelectionEvent() {
  303. console.log('[BallController] 接收到技能选择恢复事件,恢复小球运动');
  304. this.resumeAllBalls();
  305. }
  306. /**
  307. * 处理底板选择恢复事件
  308. */
  309. private onGameResumeBlockSelectionEvent() {
  310. console.log('[BallController] 接收到底板选择恢复事件,恢复小球运动');
  311. this.resumeAllBalls();
  312. }
  313. /**
  314. * 处理重置球控制器事件
  315. */
  316. private onResetBallControllerEvent() {
  317. console.log('[BallController] 接收到重置球控制器事件');
  318. this.resetBallController();
  319. }
  320. /**
  321. * 处理球创建事件
  322. */
  323. private onBallCreateEvent() {
  324. console.log('[BallController] 接收到球创建事件');
  325. this.createBall();
  326. }
  327. /**
  328. * 处理球启动事件
  329. */
  330. private onBallStartEvent() {
  331. console.log('[BallController] 接收到球启动事件');
  332. this.startBall();
  333. }
  334. /**
  335. * 处理创建额外球事件
  336. */
  337. private onBallCreateAdditionalEvent() {
  338. console.log('[BallController] 接收到创建额外球事件');
  339. this.createAdditionalBall();
  340. }
  341. /**
  342. * 处理子弹发射检查事件
  343. */
  344. private onBallFireBulletEvent(blockNode: Node, fireWorldPos: Vec3) {
  345. // 如果游戏暂停,则不允许发射子弹
  346. if (this.isPaused) {
  347. console.log('[BallController] 游戏暂停中,阻止子弹发射');
  348. return;
  349. }
  350. // 如果游戏未暂停,则继续执行子弹发射逻辑
  351. this.fireBulletAt(blockNode, fireWorldPos);
  352. }
  353. /**
  354. * 处理方块拖拽开始事件
  355. */
  356. private onBlockDragStartEvent(data: { block: Node }) {
  357. if (data && data.block) {
  358. console.log('[BallController] 方块开始拖拽:', data.block.name, '路径:', this.getNodePath(data.block));
  359. this.draggingBlocks.add(data.block);
  360. console.log('[BallController] 当前拖拽方块数量:', this.draggingBlocks.size);
  361. }
  362. }
  363. /**
  364. * 处理方块拖拽结束事件
  365. */
  366. private onBlockDragEndEvent(data: { block: Node }) {
  367. if (data && data.block) {
  368. console.log('[BallController] 方块结束拖拽:', data.block.name, '路径:', this.getNodePath(data.block));
  369. const wasDeleted = this.draggingBlocks.delete(data.block);
  370. console.log('[BallController] 删除成功:', wasDeleted, '当前拖拽方块数量:', this.draggingBlocks.size);
  371. }
  372. }
  373. /**
  374. * 调试方法:显示当前拖拽的方块
  375. */
  376. private debugDraggingBlocks() {
  377. console.log('[BallController] 当前拖拽方块列表:');
  378. this.draggingBlocks.forEach((block, index) => {
  379. // console.log(` ${index + 1}. ${block.name} - 路径: ${this.getNodePath(block)} - 有效: ${block.isValid}`);
  380. });
  381. }
  382. // 计算游戏边界(使用GameArea节点)
  383. calculateGameBounds() {
  384. // 获取GameArea节点
  385. const gameArea = find('Canvas/GameLevelUI/GameArea');
  386. if (!gameArea) {
  387. return;
  388. }
  389. const gameAreaUI = gameArea.getComponent(UITransform);
  390. if (!gameAreaUI) {
  391. return;
  392. }
  393. // 获取GameArea的尺寸
  394. const areaWidth = gameAreaUI.width;
  395. const areaHeight = gameAreaUI.height;
  396. // 获取GameArea的世界坐标位置
  397. const worldPos = gameArea.worldPosition;
  398. // 计算GameArea的世界坐标边界
  399. this.gameBounds.left = worldPos.x - areaWidth / 2;
  400. this.gameBounds.right = worldPos.x + areaWidth / 2;
  401. this.gameBounds.bottom = worldPos.y - areaHeight / 2;
  402. this.gameBounds.top = worldPos.y + areaHeight / 2;
  403. }
  404. // 创建小球
  405. createBall() {
  406. if (!this.ballPrefab) {
  407. console.error('[BallController] ballPrefab 未设置,无法创建小球');
  408. return;
  409. }
  410. // 实例化小球
  411. this.activeBall = instantiate(this.ballPrefab);
  412. if (!this.activeBall) {
  413. console.error('[BallController] 小球实例化失败');
  414. return;
  415. }
  416. // 将小球添加到GameArea中
  417. const gameArea = find('Canvas/GameLevelUI/GameArea');
  418. if (gameArea) {
  419. gameArea.addChild(this.activeBall);
  420. } else {
  421. console.warn('[BallController] 未找到GameArea,将小球添加到当前节点');
  422. this.node.addChild(this.activeBall);
  423. }
  424. // 随机位置小球
  425. this.positionBallRandomly();
  426. // 设置球的半径
  427. const transform = this.activeBall.getComponent(UITransform);
  428. if (transform) {
  429. this.radius = transform.width / 2;
  430. } else {
  431. this.radius = 25; // 默认半径
  432. }
  433. // 确保有碰撞组件
  434. this.setupCollider();
  435. // 注意:不在这里初始化方向,等待 startBall() 调用
  436. this.initialized = true;
  437. }
  438. // 创建额外的小球(不替换现有的小球)
  439. public createAdditionalBall() {
  440. if (!this.ballPrefab) {
  441. console.error('无法创建额外小球:ballPrefab 未设置');
  442. return;
  443. }
  444. // 实例化新的小球
  445. const newBall = instantiate(this.ballPrefab);
  446. newBall.name = 'AdditionalBall';
  447. // 将小球添加到GameArea中
  448. const gameArea = find('Canvas/GameLevelUI/GameArea');
  449. if (gameArea) {
  450. gameArea.addChild(newBall);
  451. } else {
  452. this.node.addChild(newBall);
  453. }
  454. // 随机位置小球
  455. this.positionAdditionalBall(newBall);
  456. // 设置球的碰撞组件
  457. this.setupBallCollider(newBall);
  458. // 设置初始方向和速度
  459. this.initializeBallDirection(newBall);
  460. console.log('创建了额外的小球');
  461. return newBall;
  462. }
  463. // 为额外小球设置随机位置
  464. private positionAdditionalBall(ball: Node) {
  465. if (!ball) return;
  466. const transform = ball.getComponent(UITransform);
  467. const ballRadius = transform ? transform.width / 2 : this.ballRadius;
  468. // 计算可生成的范围(考虑小球半径,避免生成在边缘)
  469. const minX = this.gameBounds.left + ballRadius + this.edgeOffset;
  470. const maxX = this.gameBounds.right - ballRadius - this.edgeOffset;
  471. const minY = this.gameBounds.bottom + ballRadius + this.edgeOffset;
  472. const maxY = this.gameBounds.top - ballRadius - this.edgeOffset;
  473. // 获取GameArea节点
  474. const gameArea = find('Canvas/GameLevelUI/GameArea');
  475. if (!gameArea) {
  476. return;
  477. }
  478. // 随机生成位置
  479. const randomX = Math.random() * (maxX - minX) + minX;
  480. const randomY = Math.random() * (maxY - minY) + minY;
  481. // 将世界坐标转换为相对于GameArea的本地坐标
  482. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  483. ball.position = localPos;
  484. }
  485. // 为额外小球设置碰撞组件
  486. private setupBallCollider(ball: Node) {
  487. // 确保有碰撞组件
  488. let collider = ball.getComponent(CircleCollider2D);
  489. if (!collider) {
  490. collider = ball.addComponent(CircleCollider2D);
  491. }
  492. // 设置碰撞属性(使用配置值)
  493. collider.radius = this.ballRadius;
  494. collider.group = this.colliderGroup;
  495. collider.tag = this.colliderTag;
  496. collider.sensor = this.sensor;
  497. collider.friction = this.friction;
  498. collider.restitution = this.restitution;
  499. // 添加刚体组件
  500. let rigidBody = ball.getComponent(RigidBody2D);
  501. if (!rigidBody) {
  502. rigidBody = ball.addComponent(RigidBody2D);
  503. }
  504. // 设置刚体属性(使用配置值)
  505. rigidBody.type = ERigidBody2DType.Dynamic; // 动态刚体
  506. rigidBody.allowSleep = false;
  507. rigidBody.gravityScale = this.gravityScale;
  508. rigidBody.linearDamping = this.linearDamping;
  509. rigidBody.angularDamping = this.angularDamping;
  510. rigidBody.fixedRotation = true;
  511. rigidBody.enabledContactListener = true; // 启用碰撞监听
  512. // 注意:不需要为每个小球单独添加碰撞回调,
  513. // 因为我们使用的是全局物理系统回调
  514. }
  515. // 为额外小球初始化方向和速度
  516. private initializeBallDirection(ball: Node) {
  517. // 随机初始方向
  518. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  519. const direction = new Vec2(Math.cos(angle), Math.sin(angle)).normalize();
  520. // 设置初始速度
  521. const rigidBody = ball.getComponent(RigidBody2D);
  522. if (rigidBody) {
  523. rigidBody.linearVelocity = new Vec2(
  524. direction.x * this.currentSpeed,
  525. direction.y * this.currentSpeed
  526. );
  527. }
  528. }
  529. // 检查所有已放置方块的碰撞体组件
  530. private checkBlockColliders() {
  531. if (!this.placedBlocksContainer) {
  532. return;
  533. }
  534. if (!this.placedBlocksContainer.isValid) {
  535. return;
  536. }
  537. const blocks = [];
  538. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  539. const block = this.placedBlocksContainer.children[i];
  540. if (block.name.includes('Block') || block.getChildByName('B1')) {
  541. blocks.push(block);
  542. }
  543. }
  544. let fixedCount = 0;
  545. for (let i = 0; i < blocks.length; i++) {
  546. const block = blocks[i];
  547. // 检查方块本身的碰撞体
  548. const blockCollider = block.getComponent(Collider2D);
  549. if (blockCollider) {
  550. // 🔧 自动修复碰撞组设置
  551. if (blockCollider.group !== 2) {
  552. blockCollider.group = 2; // 设置为Block组
  553. fixedCount++;
  554. }
  555. // 确保不是传感器
  556. if (blockCollider.sensor) {
  557. blockCollider.sensor = false;
  558. }
  559. }
  560. // 检查B1子节点的碰撞体
  561. const b1Node = block.getChildByName('B1');
  562. if (b1Node) {
  563. const b1Collider = b1Node.getComponent(Collider2D);
  564. if (b1Collider) {
  565. // 🔧 修复B1子节点的碰撞设置
  566. if (b1Collider.group !== 2) {
  567. b1Collider.group = 2; // 设置为Block组
  568. fixedCount++;
  569. }
  570. // 确保B1不是传感器(需要实际碰撞)
  571. if (b1Collider.sensor) {
  572. b1Collider.sensor = false;
  573. }
  574. }
  575. }
  576. // 检查Weapon子节点
  577. const weaponNode = this.findWeaponNode(block);
  578. if (weaponNode) {
  579. // 武器节点存在
  580. }
  581. }
  582. }
  583. // 随机位置小球
  584. positionBallRandomly() {
  585. if (!this.activeBall) return;
  586. const transform = this.activeBall.getComponent(UITransform);
  587. const ballRadius = transform ? transform.width / 2 : this.ballRadius;
  588. // 计算可生成的范围(考虑小球半径,避免生成在边缘)
  589. const minX = this.gameBounds.left + ballRadius + this.edgeOffset; // 额外偏移,避免生成在边缘
  590. const maxX = this.gameBounds.right - ballRadius - this.edgeOffset;
  591. const minY = this.gameBounds.bottom + ballRadius + this.edgeOffset;
  592. const maxY = this.gameBounds.top - ballRadius - this.edgeOffset;
  593. // 获取GameArea节点
  594. const gameArea = find('Canvas/GameLevelUI/GameArea');
  595. if (!gameArea) {
  596. return;
  597. }
  598. // 查找PlacedBlocks节点,它包含所有放置的方块
  599. if (!this.placedBlocksContainer) {
  600. this.setRandomPositionDefault(this.activeBall, minX, maxX, minY, maxY);
  601. return;
  602. }
  603. // 获取所有已放置的方块
  604. const placedBlocks = [];
  605. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  606. const block = this.placedBlocksContainer.children[i];
  607. // 检查是否是方块节点(通常以Block命名或有特定标识)
  608. if (block.name.includes('Block') || block.getChildByName('B1')) {
  609. placedBlocks.push(block);
  610. }
  611. }
  612. // 如果没有方块,使用默认随机位置
  613. if (placedBlocks.length === 0) {
  614. this.setRandomPositionDefault(this.activeBall, minX, maxX, minY, maxY);
  615. return;
  616. }
  617. // 尝试找到一个不与任何方块重叠的位置
  618. let validPosition = false;
  619. let attempts = 0;
  620. const maxAttempts = this.maxAttempts; // 从配置中获取最大尝试次数
  621. let randomX, randomY;
  622. while (!validPosition && attempts < maxAttempts) {
  623. // 随机生成位置
  624. randomX = Math.random() * (maxX - minX) + minX;
  625. randomY = Math.random() * (maxY - minY) + minY;
  626. // 检查是否与任何方块重叠
  627. let overlapping = false;
  628. for (const block of placedBlocks) {
  629. // 获取方块的世界坐标
  630. const blockWorldPos = block.worldPosition;
  631. // 计算小球与方块的距离
  632. const distance = Math.sqrt(
  633. Math.pow(randomX - blockWorldPos.x, 2) +
  634. Math.pow(randomY - blockWorldPos.y, 2)
  635. );
  636. // 获取方块的尺寸
  637. const blockTransform = block.getComponent(UITransform);
  638. const blockSize = blockTransform ?
  639. Math.max(blockTransform.width, blockTransform.height) / 2 : this.safeDistance;
  640. // 如果距离小于小球半径+方块尺寸的一半+安全距离,认为重叠
  641. if (distance < ballRadius + blockSize + this.safeDistance) {
  642. overlapping = true;
  643. break;
  644. }
  645. }
  646. // 如果没有重叠,找到了有效位置
  647. if (!overlapping) {
  648. validPosition = true;
  649. }
  650. attempts++;
  651. }
  652. // 如果找不到有效位置,使用默认位置(游戏区域底部中心)
  653. if (!validPosition) {
  654. randomX = (this.gameBounds.left + this.gameBounds.right) / 2;
  655. randomY = this.gameBounds.bottom + ballRadius + this.safeDistance; // 底部上方安全距离单位
  656. }
  657. // 将世界坐标转换为相对于GameArea的本地坐标
  658. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  659. this.activeBall.position = localPos;
  660. }
  661. // 设置碰撞组件
  662. setupCollider() {
  663. if (!this.activeBall) return;
  664. // 确保小球有刚体组件
  665. let rigidBody = this.activeBall.getComponent(RigidBody2D);
  666. if (!rigidBody) {
  667. rigidBody = this.activeBall.addComponent(RigidBody2D);
  668. rigidBody.type = ERigidBody2DType.Dynamic; // Dynamic
  669. rigidBody.gravityScale = this.gravityScale; // 从配置获取重力缩放
  670. rigidBody.enabledContactListener = true; // 启用碰撞监听
  671. rigidBody.fixedRotation = true; // 固定旋转
  672. rigidBody.allowSleep = false; // 不允许休眠
  673. rigidBody.linearDamping = this.linearDamping; // 从配置获取线性阻尼
  674. rigidBody.angularDamping = this.angularDamping; // 从配置获取角阻尼
  675. } else {
  676. // 确保已有的刚体组件设置正确
  677. rigidBody.enabledContactListener = true;
  678. rigidBody.gravityScale = this.gravityScale;
  679. rigidBody.linearDamping = this.linearDamping; // 从配置获取线性阻尼
  680. rigidBody.angularDamping = this.angularDamping; // 从配置获取角阻尼
  681. rigidBody.allowSleep = false; // 不允许休眠
  682. }
  683. // 确保小球有碰撞组件
  684. let collider = this.activeBall.getComponent(CircleCollider2D);
  685. if (!collider) {
  686. collider = this.activeBall.addComponent(CircleCollider2D);
  687. collider.radius = this.radius || this.ballRadius; // 使用已计算的半径或配置值
  688. collider.tag = this.colliderTag; // 从配置获取小球标签
  689. collider.group = this.colliderGroup; // 从配置获取碰撞组
  690. collider.sensor = this.sensor; // 从配置获取传感器设置
  691. collider.friction = this.friction; // 从配置获取摩擦系数
  692. collider.restitution = this.restitution; // 从配置获取恢复系数
  693. } else {
  694. // 确保已有的碰撞组件设置正确
  695. collider.sensor = this.sensor;
  696. collider.restitution = this.restitution;
  697. collider.group = this.colliderGroup; // 从配置获取碰撞组
  698. collider.tag = this.colliderTag; // 从配置获取标签
  699. }
  700. // === 使用全局回调监听器 ===
  701. const physics = PhysicsManager.getInstance()?.getSystem();
  702. if (physics) {
  703. // 先移除旧监听,避免重复注册
  704. physics.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  705. // 只注册实际需要的碰撞开始事件
  706. physics.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  707. }
  708. }
  709. // 碰撞回调 - 处理小球与方块以及小球之间的碰撞
  710. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  711. // 检查是否为小球之间的碰撞
  712. if (selfCollider.group === 1 && otherCollider.group === 1) {
  713. // 小球之间的碰撞 - 防止速度改变
  714. this.handleBallToBallCollision(selfCollider, otherCollider, contact);
  715. return;
  716. }
  717. // 判断哪个是小球,哪个是碰撞对象
  718. let ballNode: Node = null;
  719. let otherNode: Node = null;
  720. // 检查self是否为小球(组1)
  721. if (selfCollider.group === 1) {
  722. ballNode = selfCollider.node;
  723. otherNode = otherCollider.node;
  724. }
  725. // 检查other是否为小球(组1)
  726. else if (otherCollider.group === 1) {
  727. ballNode = otherCollider.node;
  728. otherNode = selfCollider.node;
  729. }
  730. // 如果没有找到小球,跳过处理
  731. if (!ballNode || !otherNode) {
  732. return;
  733. }
  734. // 检查是否为方块碰撞
  735. const nodeName = otherNode.name;
  736. const nodePath = this.getNodePath(otherNode);
  737. // 根据新的预制体结构,检查B1/Weapon路径
  738. const b1Node = otherNode.getChildByName('B1');
  739. const hasWeaponChild = b1Node ? b1Node.getChildByName('Weapon') !== null : otherNode.getChildByName('Weapon') !== null;
  740. const isBlock =
  741. nodeName.includes('Block') ||
  742. nodePath.includes('Block') ||
  743. hasWeaponChild;
  744. // 如果是方块碰撞,检查防围困机制
  745. if (isBlock) {
  746. // 检查方块是否正在被拖拽,如果是则忽略碰撞
  747. // 需要检查碰撞节点本身或其父节点是否在拖拽列表中
  748. let isDragging = false;
  749. let currentNode = otherNode;
  750. // 向上遍历节点树,检查是否有父节点在拖拽列表中
  751. while (currentNode && !isDragging) {
  752. if (this.draggingBlocks.has(currentNode)) {
  753. isDragging = true;
  754. console.log('[BallController] 发现拖拽方块,忽略碰撞:', currentNode.name, '碰撞节点:', otherNode.name, '路径:', nodePath);
  755. break;
  756. }
  757. currentNode = currentNode.parent;
  758. }
  759. if (isDragging) {
  760. console.log('[BallController] 当前拖拽方块数量:', this.draggingBlocks.size);
  761. if (contact) {
  762. contact.disabled = true;
  763. }
  764. return;
  765. }
  766. const ballId = ballNode.uuid;
  767. const currentTime = performance.now() / 1000; // 转换为秒
  768. // 检查是否处于穿透状态
  769. const phaseThroughEndTime = this.ballPhaseThrough.get(ballId);
  770. if (phaseThroughEndTime && currentTime < phaseThroughEndTime) {
  771. // 处于穿透状态,忽略碰撞但仍播放特效
  772. const ballAni = BallAni.getInstance();
  773. if (ballAni) {
  774. let contactPos: Vec3 = null;
  775. if (contact && (contact as any).getWorldManifold) {
  776. const wm = (contact as any).getWorldManifold();
  777. if (wm && wm.points && wm.points.length > 0) {
  778. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  779. }
  780. }
  781. if (!contactPos) {
  782. contactPos = otherNode.worldPosition.clone();
  783. }
  784. ballAni.playImpactEffect(contactPos);
  785. }
  786. // 禁用碰撞
  787. if (contact) {
  788. contact.disabled = true;
  789. }
  790. return;
  791. }
  792. // 记录撞击历史
  793. if (!this.ballHitHistory.has(ballId)) {
  794. this.ballHitHistory.set(ballId, []);
  795. }
  796. const hitHistory = this.ballHitHistory.get(ballId);
  797. hitHistory.push(currentTime);
  798. // 清理过期的撞击记录
  799. const timeThreshold = currentTime - this.antiTrapTimeWindow;
  800. while (hitHistory.length > 0 && hitHistory[0] < timeThreshold) {
  801. hitHistory.shift();
  802. }
  803. // 测试模式:显示详细的防围困信息
  804. // console.log(`[BallController] 测试模式 - 小球撞击统计: 撞击次数=${hitHistory.length}/${this.antiTrapHitThreshold}, 时间窗口=${this.antiTrapTimeWindow}秒, 方块=${otherNode.name}`);
  805. // 检查是否达到防围困条件
  806. if (hitHistory.length >= this.antiTrapHitThreshold) {
  807. //console.log(`[BallController] 测试模式 - 触发防围困机制! 撞击次数已达到阈值 ${this.antiTrapHitThreshold}`);
  808. // 获取当前偏移尝试次数
  809. const deflectionAttempts = this.ballDeflectionAttempts.get(ballId) || 0;
  810. if (deflectionAttempts < this.deflectionAttemptThreshold) {
  811. // 优先使用偏移方式
  812. this.ballDeflectionAttempts.set(ballId, deflectionAttempts + 1);
  813. //console.log(`[BallController] 测试模式 - 应用防围困偏移 (第${deflectionAttempts + 1}/${this.deflectionAttemptThreshold}次尝试)`);
  814. // 应用增强偏移反弹
  815. const rigidBody = ballNode.getComponent(RigidBody2D);
  816. if (rigidBody && contact) {
  817. // 获取碰撞法线
  818. let normal = new Vec2(0, 1);
  819. if ((contact as any).getWorldManifold) {
  820. const wm = (contact as any).getWorldManifold();
  821. if (wm && wm.normal) {
  822. normal = new Vec2(wm.normal.x, wm.normal.y);
  823. }
  824. }
  825. // 计算增强偏移反弹方向
  826. const currentVelocity = rigidBody.linearVelocity;
  827. const currentDirection = new Vec2(currentVelocity.x, currentVelocity.y).normalize();
  828. const oldDirection = `(${currentDirection.x.toFixed(2)}, ${currentDirection.y.toFixed(2)})`;
  829. const newDirection = this.calculateAntiTrapReflection(currentDirection, normal);
  830. const newDirectionStr = `(${newDirection.x.toFixed(2)}, ${newDirection.y.toFixed(2)})`;
  831. console.log(`[BallController] 测试模式 - 方向改变: ${oldDirection} -> ${newDirectionStr}`);
  832. // 应用新的速度方向
  833. const speed = currentVelocity.length();
  834. rigidBody.linearVelocity = new Vec2(newDirection.x * speed, newDirection.y * speed);
  835. }
  836. // 清空撞击历史,给偏移一个机会
  837. hitHistory.length = 0;
  838. } else {
  839. // 偏移尝试次数已达上限,使用穿透
  840. console.log(`[BallController] 测试模式 - 偏移尝试已达上限,启用穿透模式 (0.5秒)`);
  841. this.ballPhaseThrough.set(ballId, currentTime + 0.5);
  842. // 重置偏移尝试次数
  843. this.ballDeflectionAttempts.set(ballId, 0);
  844. // 清空撞击历史
  845. hitHistory.length = 0;
  846. // 禁用当前碰撞
  847. if (contact) {
  848. contact.disabled = true;
  849. }
  850. return;
  851. }
  852. }
  853. }
  854. // 计算碰撞世界坐标
  855. let contactPos: Vec3 = null;
  856. if (contact && (contact as any).getWorldManifold) {
  857. const wm = (contact as any).getWorldManifold();
  858. if (wm && wm.points && wm.points.length > 0) {
  859. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  860. }
  861. }
  862. if (!contactPos) {
  863. contactPos = otherNode.worldPosition.clone();
  864. }
  865. // 播放撞击特效 - 对所有碰撞都播放特效
  866. const ballAni = BallAni.getInstance();
  867. if (ballAni) {
  868. ballAni.playImpactEffect(contactPos);
  869. }
  870. if (isBlock) {
  871. // 播放方块撞击动画
  872. if (ballAni) {
  873. ballAni.playBlockHitAnimation(otherNode);
  874. }
  875. // 通过事件检查是否可以发射子弹
  876. const eventBus = EventBus.getInstance();
  877. let canFire = true;
  878. // 发送检查事件,如果有监听器返回false则不发射
  879. eventBus.emit(GameEvents.BALL_FIRE_BULLET, { canFire: (value: boolean) => { canFire = value; } });
  880. if (canFire) {
  881. const now = performance.now();
  882. const lastTime = this.blockFireCooldown.get(otherNode.uuid) || 0;
  883. if (now - lastTime > this.FIRE_COOLDOWN * 1000) {
  884. this.blockFireCooldown.set(otherNode.uuid, now);
  885. this.fireBulletAt(otherNode, contactPos);
  886. }
  887. }
  888. }
  889. }
  890. /**
  891. * 处理小球之间的碰撞 - 保持恒定速度
  892. */
  893. private handleBallToBallCollision(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  894. const ball1 = selfCollider.node;
  895. const ball2 = otherCollider.node;
  896. const rigidBody1 = ball1.getComponent(RigidBody2D);
  897. const rigidBody2 = ball2.getComponent(RigidBody2D);
  898. if (!rigidBody1 || !rigidBody2) {
  899. return;
  900. }
  901. // 计算碰撞位置并播放撞击特效
  902. let contactPos: Vec3 = null;
  903. if (contact && (contact as any).getWorldManifold) {
  904. const wm = (contact as any).getWorldManifold();
  905. if (wm && wm.points && wm.points.length > 0) {
  906. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  907. }
  908. }
  909. if (!contactPos) {
  910. // 使用两个小球位置的中点作为碰撞位置
  911. const pos1 = ball1.worldPosition;
  912. const pos2 = ball2.worldPosition;
  913. contactPos = new Vec3(
  914. (pos1.x + pos2.x) / 2,
  915. (pos1.y + pos2.y) / 2,
  916. 0
  917. );
  918. }
  919. // 播放撞击特效
  920. const ballAni = BallAni.getInstance();
  921. if (ballAni) {
  922. ballAni.playImpactEffect(contactPos);
  923. }
  924. // 获取碰撞前的速度
  925. const velocity1 = rigidBody1.linearVelocity.clone();
  926. const velocity2 = rigidBody2.linearVelocity.clone();
  927. // 计算速度大小
  928. const speed1 = Math.sqrt(velocity1.x * velocity1.x + velocity1.y * velocity1.y);
  929. const speed2 = Math.sqrt(velocity2.x * velocity2.x + velocity2.y * velocity2.y);
  930. // 延迟一帧后恢复正确的速度,避免物理引擎的速度改变
  931. this.scheduleOnce(() => {
  932. if (ball1.isValid && rigidBody1.isValid) {
  933. const currentVel1 = rigidBody1.linearVelocity;
  934. const currentSpeed1 = Math.sqrt(currentVel1.x * currentVel1.x + currentVel1.y * currentVel1.y);
  935. // 如果速度发生了显著变化,恢复到目标速度
  936. if (Math.abs(currentSpeed1 - this.currentSpeed) > 5) {
  937. const normalizedVel1 = currentVel1.clone().normalize();
  938. rigidBody1.linearVelocity = new Vec2(
  939. normalizedVel1.x * this.currentSpeed,
  940. normalizedVel1.y * this.currentSpeed
  941. );
  942. }
  943. }
  944. if (ball2.isValid && rigidBody2.isValid) {
  945. const currentVel2 = rigidBody2.linearVelocity;
  946. const currentSpeed2 = Math.sqrt(currentVel2.x * currentVel2.x + currentVel2.y * currentVel2.y);
  947. // 如果速度发生了显著变化,恢复到目标速度
  948. if (Math.abs(currentSpeed2 - this.currentSpeed) > 5) {
  949. const normalizedVel2 = currentVel2.clone().normalize();
  950. rigidBody2.linearVelocity = new Vec2(
  951. normalizedVel2.x * this.currentSpeed,
  952. normalizedVel2.y * this.currentSpeed
  953. );
  954. }
  955. }
  956. }, 0.016); // 约一帧的时间
  957. }
  958. // 计算反射向量
  959. calculateReflection(direction: Vec2, normal: Vec2): Vec2 {
  960. // 使用反射公式: R = V - 2(V·N)N
  961. const dot = direction.x * normal.x + direction.y * normal.y;
  962. const reflection = new Vec2(
  963. direction.x - 2 * dot * normal.x,
  964. direction.y - 2 * dot * normal.y
  965. );
  966. reflection.normalize();
  967. // 添加一些随机性,避免重复的反弹路径
  968. const randomAngle = (Math.random() - 0.5) * this.maxReflectionRandomness; // 随机角度
  969. const cos = Math.cos(randomAngle);
  970. const sin = Math.sin(randomAngle);
  971. // 应用随机旋转
  972. const randomizedReflection = new Vec2(
  973. reflection.x * cos - reflection.y * sin,
  974. reflection.x * sin + reflection.y * cos
  975. );
  976. // 更强的防水平/垂直往复运动机制
  977. // 增大最小角度阈值,并添加更强的随机偏移
  978. const minAngleFromAxis = 0.5; // 从0.3增加到0.5,约28.6度
  979. const strongRandomOffset = 0.2; // 增加随机偏移范围
  980. // 检查是否接近水平方向(y分量过小)
  981. if (Math.abs(randomizedReflection.y) < minAngleFromAxis) {
  982. // 调整y分量,使其远离水平方向,并添加更大的随机偏移
  983. const sign = randomizedReflection.y >= 0 ? 1 : -1;
  984. randomizedReflection.y = sign * (minAngleFromAxis + Math.random() * strongRandomOffset);
  985. // 重新归一化
  986. randomizedReflection.normalize();
  987. }
  988. // 检查是否接近垂直方向(x分量过小)
  989. if (Math.abs(randomizedReflection.x) < minAngleFromAxis) {
  990. // 调整x分量,使其远离垂直方向,并添加更大的随机偏移
  991. const sign = randomizedReflection.x >= 0 ? 1 : -1;
  992. randomizedReflection.x = sign * (minAngleFromAxis + Math.random() * strongRandomOffset);
  993. // 重新归一化
  994. randomizedReflection.normalize();
  995. }
  996. // 额外检查:如果仍然太接近轴向,强制添加对角分量
  997. const finalCheck = 0.4;
  998. if (Math.abs(randomizedReflection.y) < finalCheck || Math.abs(randomizedReflection.x) < finalCheck) {
  999. // 强制添加对角分量,确保既有x又有y的显著分量
  1000. const angle = Math.PI / 4 + (Math.random() - 0.5) * Math.PI / 6; // 45度±15度
  1001. const signX = randomizedReflection.x >= 0 ? 1 : -1;
  1002. const signY = randomizedReflection.y >= 0 ? 1 : -1;
  1003. randomizedReflection.x = signX * Math.cos(angle);
  1004. randomizedReflection.y = signY * Math.sin(angle);
  1005. }
  1006. randomizedReflection.normalize();
  1007. return randomizedReflection;
  1008. }
  1009. /**
  1010. * 计算防围困增强偏移反弹方向
  1011. * @param direction 当前方向
  1012. * @param normal 碰撞法线
  1013. * @returns 增强偏移后的反弹方向
  1014. */
  1015. calculateAntiTrapReflection(direction: Vec2, normal: Vec2): Vec2 {
  1016. // 使用反射公式: R = V - 2(V·N)N
  1017. const dot = direction.x * normal.x + direction.y * normal.y;
  1018. const reflection = new Vec2(
  1019. direction.x - 2 * dot * normal.x,
  1020. direction.y - 2 * dot * normal.y
  1021. );
  1022. reflection.normalize();
  1023. // 应用更强的随机偏移来帮助脱困
  1024. const enhancedRandomness = this.maxReflectionRandomness * this.antiTrapDeflectionMultiplier;
  1025. const randomAngle = (Math.random() - 0.5) * enhancedRandomness;
  1026. const cos = Math.cos(randomAngle);
  1027. const sin = Math.sin(randomAngle);
  1028. // 应用随机旋转
  1029. const randomizedReflection = new Vec2(
  1030. reflection.x * cos - reflection.y * sin,
  1031. reflection.x * sin + reflection.y * cos
  1032. );
  1033. // 更强的轴向偏移避免
  1034. const minAngleFromAxis = 0.3; // 约17度,比普通反弹更大的偏移
  1035. // 检查是否接近水平方向
  1036. if (Math.abs(randomizedReflection.y) < minAngleFromAxis) {
  1037. const sign = randomizedReflection.y >= 0 ? 1 : -1;
  1038. randomizedReflection.y = sign * (minAngleFromAxis + Math.random() * 0.2);
  1039. randomizedReflection.normalize();
  1040. }
  1041. // 检查是否接近垂直方向
  1042. if (Math.abs(randomizedReflection.x) < minAngleFromAxis) {
  1043. const sign = randomizedReflection.x >= 0 ? 1 : -1;
  1044. randomizedReflection.x = sign * (minAngleFromAxis + Math.random() * 0.2);
  1045. randomizedReflection.normalize();
  1046. }
  1047. randomizedReflection.normalize();
  1048. console.log(`Applied anti-trap enhanced deflection with angle: ${randomAngle}`);
  1049. return randomizedReflection;
  1050. }
  1051. /**
  1052. * 从方块武器发射子弹攻击敌人 - 重构版本
  1053. * 现在直接创建子弹实例并使用BulletController的实例方法
  1054. * @param blockNode 激活的方块节点
  1055. */
  1056. fireBullet(blockNode: Node) {
  1057. // 检查子弹预制体是否存在
  1058. if (!this.bulletPrefab) {
  1059. return;
  1060. }
  1061. // 查找方块中的Weapon节点
  1062. const weaponNode = this.findWeaponNode(blockNode);
  1063. let firePosition: Vec3;
  1064. if (!weaponNode) {
  1065. firePosition = blockNode.worldPosition;
  1066. } else {
  1067. // 获取武器的世界坐标作为发射位置
  1068. try {
  1069. firePosition = weaponNode.worldPosition;
  1070. } catch (error) {
  1071. // 备用方案:使用方块坐标
  1072. firePosition = blockNode.worldPosition;
  1073. }
  1074. }
  1075. // 通过事件系统发射子弹,这样可以被暂停检查拦截
  1076. EventBus.getInstance().emit(GameEvents.BALL_FIRE_BULLET, blockNode, firePosition);
  1077. }
  1078. /**
  1079. * 创建并发射子弹 - 使用新的WeaponBullet系统
  1080. * @param firePosition 发射位置(世界坐标)
  1081. * @param weaponNode 武器节点(包含WeaponInfo组件)
  1082. * @param sourceBlock 发射源方块节点(用于回旋镖返回)
  1083. */
  1084. private createAndFireBullet(firePosition: Vec3, weaponNode: Node | null, sourceBlock?: Node) {
  1085. // 确保武器配置加载
  1086. WeaponBullet.loadWeaponsData().then(() => {
  1087. let finalConfig: WeaponConfig | null = null;
  1088. // 优先从武器节点的WeaponInfo组件获取配置
  1089. if (weaponNode && weaponNode.isValid) {
  1090. const weaponInfo = weaponNode.getComponent(WeaponInfo);
  1091. if (weaponInfo) {
  1092. finalConfig = weaponInfo.getWeaponConfig();
  1093. console.log(`[BallController] 从武器节点获取武器配置: ${finalConfig?.name || '未知'}`);
  1094. // 检查武器是否可以开火
  1095. if (!weaponInfo.canFire()) {
  1096. console.log(`[BallController] 武器 ${finalConfig?.name || '未知'} 冷却中,无法开火`);
  1097. return;
  1098. }
  1099. // 记录开火时间
  1100. weaponInfo.recordFireTime();
  1101. }
  1102. }
  1103. // 如果没有从武器节点获取到配置,使用默认配置
  1104. if (!finalConfig) {
  1105. const defaultWeaponId = 'pea_shooter';
  1106. finalConfig = WeaponBullet.getWeaponConfig(defaultWeaponId);
  1107. console.log(`[BallController] 使用默认武器配置: ${defaultWeaponId}`);
  1108. }
  1109. if (!finalConfig) {
  1110. console.warn(`[BallController] 无法获取武器配置,取消发射`);
  1111. return;
  1112. }
  1113. // 获取WeaponInfo组件(如果有的话)
  1114. let weaponInfoComponent: WeaponInfo | null = null;
  1115. if (weaponNode && weaponNode.isValid) {
  1116. weaponInfoComponent = weaponNode.getComponent(WeaponInfo);
  1117. }
  1118. // 获取BlockInfo组件(如果有的话)
  1119. // BlockInfo组件位于方块的Node子节点上,而不是Weapon子节点上
  1120. let blockInfoComponent: BlockInfo | null = null;
  1121. if (weaponNode && weaponNode.isValid && weaponNode.parent) {
  1122. // 从weaponNode的父节点(方块根节点)查找Node子节点
  1123. const blockRootNode = weaponNode.parent;
  1124. const nodeChild = blockRootNode.getChildByName('Node');
  1125. if (nodeChild) {
  1126. blockInfoComponent = nodeChild.getComponent(BlockInfo);
  1127. if (blockInfoComponent) {
  1128. console.log(`[BallController] 找到BlockInfo组件,稀有度等级: ${blockInfoComponent.rarity}, 稀有度名称: ${blockInfoComponent.getRarityName()}`);
  1129. } else {
  1130. console.log(`[BallController] Node子节点上未找到BlockInfo组件`);
  1131. }
  1132. } else {
  1133. console.log(`[BallController] 未找到Node子节点`);
  1134. }
  1135. // 如果还是没找到,尝试直接从weaponNode上获取(兼容旧结构)
  1136. if (!blockInfoComponent) {
  1137. blockInfoComponent = weaponNode.getComponent(BlockInfo);
  1138. if (blockInfoComponent) {
  1139. console.log(`[BallController] 从weaponNode上找到BlockInfo组件,稀有度等级: ${blockInfoComponent.rarity}, 稀有度名称: ${blockInfoComponent.getRarityName()}`);
  1140. } else {
  1141. console.log(`[BallController] 未找到BlockInfo组件,将使用JSON配置中的稀有度`);
  1142. }
  1143. }
  1144. }
  1145. // 创建子弹初始化数据
  1146. const initData: BulletInitData = {
  1147. weaponId: finalConfig.id,
  1148. firePosition: firePosition,
  1149. autoTarget: true,
  1150. weaponConfig: finalConfig,
  1151. weaponInfo: weaponInfoComponent,
  1152. blockInfo: blockInfoComponent,
  1153. sourceBlock: sourceBlock // 传递发射源方块节点
  1154. };
  1155. // 验证初始化数据
  1156. if (!WeaponBullet.validateInitData(initData)) {
  1157. console.warn(`[BallController] 子弹初始化数据验证失败`);
  1158. return;
  1159. }
  1160. // 查找GameArea(子弹统一添加到此节点)
  1161. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1162. if (!gameArea) {
  1163. console.warn(`[BallController] 未找到GameArea节点,无法发射子弹`);
  1164. return;
  1165. }
  1166. // === 根据武器配置选择合适的预制体 ===
  1167. const trailEffect = finalConfig.bulletConfig?.visual?.trailEffect;
  1168. // 尖胡萝卜特殊处理:使用PelletContainer预制体但激活Spine节点
  1169. const isSharpCarrot = finalConfig.id === 'sharp_carrot';
  1170. // 当trailEffect为true或者是尖胡萝卜时都使用容器预制体
  1171. const needsContainerPrefab = Boolean(trailEffect) || isSharpCarrot;
  1172. const prefabToUse: Prefab = (needsContainerPrefab && this.bulletContainerPrefab) ? this.bulletContainerPrefab : this.bulletPrefab;
  1173. if (!prefabToUse) {
  1174. console.warn(`[BallController] 没有可用的子弹预制体`);
  1175. return;
  1176. }
  1177. // 使用批量创建逻辑
  1178. console.log(`[BallController] 开始创建子弹 - 武器: ${finalConfig.name}, 预制体: ${prefabToUse ? prefabToUse.name : 'null'}`);
  1179. const bullets = WeaponBullet.createBullets(initData, prefabToUse as any);
  1180. console.log(`[BallController] WeaponBullet.createBullets 返回了 ${bullets.length} 个子弹`);
  1181. bullets.forEach((b, index) => {
  1182. console.log(`[BallController] 添加第 ${index + 1} 个子弹到场景 - 子弹节点: ${b ? b.name : 'null'}, 是否有效: ${b ? b.isValid : 'false'}`);
  1183. if (b && b.isValid) {
  1184. gameArea.addChild(b);
  1185. console.log(`[BallController] 子弹 ${index + 1} 成功添加到场景,世界坐标: ${b.worldPosition}`);
  1186. } else {
  1187. console.error(`[BallController] 子弹 ${index + 1} 无效,无法添加到场景`);
  1188. }
  1189. });
  1190. console.log(`[BallController] 成功发射 ${bullets.length} 发子弹,武器: ${finalConfig.name}`);
  1191. }).catch(error => {
  1192. console.error(`[BallController] 武器配置加载失败:`, error);
  1193. });
  1194. }
  1195. // 递归查找Weapon节点
  1196. private findWeaponNode(node: Node): Node | null {
  1197. // 检查节点是否有效
  1198. if (!node || !node.isValid) {
  1199. console.warn('[BallController] findWeaponNode: 传入的节点无效');
  1200. return null;
  1201. }
  1202. // 根据新的预制体结构,武器节点直接位于方块根节点下
  1203. // 首先检查当前节点是否有Weapon子节点
  1204. const weaponNode = node.getChildByName('Weapon');
  1205. if (weaponNode) {
  1206. return weaponNode;
  1207. }
  1208. // 如果当前节点没有Weapon子节点,检查父节点(可能传入的是Node子节点而不是预制体根节点)
  1209. if (node.parent) {
  1210. const parentWeaponNode = node.parent.getChildByName('Weapon');
  1211. if (parentWeaponNode) {
  1212. return parentWeaponNode;
  1213. }
  1214. }
  1215. // 最后使用递归方式查找(兼容其他可能的结构)
  1216. for (let i = 0; i < node.children.length; i++) {
  1217. const child = node.children[i];
  1218. const foundWeapon = this.findWeaponNode(child);
  1219. if (foundWeapon) {
  1220. return foundWeapon;
  1221. }
  1222. }
  1223. // 如果都没找到,返回null
  1224. console.warn('[BallController] 方块', node.name, '中未找到武器节点');
  1225. return null;
  1226. }
  1227. // 获取节点的完整路径
  1228. private getNodePath(node: Node): string {
  1229. let path = node.name;
  1230. let current = node;
  1231. while (current.parent) {
  1232. current = current.parent;
  1233. path = current.name + '/' + path;
  1234. }
  1235. return path;
  1236. }
  1237. private debugDragCounter = 0;
  1238. update(dt: number) {
  1239. // 只有当小球已启动时才执行运动逻辑
  1240. if (!this.ballStarted || !this.initialized) {
  1241. return;
  1242. }
  1243. // 维持所有小球的恒定速度
  1244. this.maintainAllBallsSpeed();
  1245. // 更新小球运动历史数据(用于检测振荡模式)
  1246. this.updateBallMovementHistory();
  1247. // 清理过期的防围困状态
  1248. this.cleanupExpiredAntiTrapStates();
  1249. // 定期检查小球位置,防止小球被挤出游戏区域
  1250. this.lastPositionCheckTime += dt;
  1251. if (this.lastPositionCheckTime >= this.positionCheckInterval) {
  1252. this.checkAndRescueAllBalls();
  1253. this.lastPositionCheckTime = 0;
  1254. }
  1255. // 定期检查小球是否接近方块但没有触发碰撞(调试用)
  1256. if (this.activeBall && this.activeBall.isValid) {
  1257. this.debugCheckNearBlocks();
  1258. }
  1259. // 定期调试拖拽状态(每5秒一次)
  1260. this.debugDragCounter += dt;
  1261. if (this.debugDragCounter >= 5.0 && this.draggingBlocks.size > 0) {
  1262. console.log('[BallController] 定期调试 - 当前拖拽状态:');
  1263. this.debugDraggingBlocks();
  1264. this.debugDragCounter = 0;
  1265. }
  1266. }
  1267. /**
  1268. * 更新小球运动历史数据(用于检测振荡模式)
  1269. */
  1270. private updateBallMovementHistory() {
  1271. if (!this.activeBall || !this.activeBall.isValid) {
  1272. return;
  1273. }
  1274. const ballId = this.activeBall.uuid;
  1275. const currentTime = Date.now() / 1000; // 转换为秒
  1276. const currentPos = this.activeBall.getWorldPosition();
  1277. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  1278. if (!rigidBody) {
  1279. return;
  1280. }
  1281. const currentVelocity = rigidBody.linearVelocity;
  1282. const currentDirection = new Vec2(currentVelocity.x, currentVelocity.y).normalize();
  1283. // 初始化历史记录
  1284. if (!this.ballPositionHistory.has(ballId)) {
  1285. this.ballPositionHistory.set(ballId, []);
  1286. this.ballDirectionHistory.set(ballId, []);
  1287. this.ballOscillationDetection.set(ballId, {
  1288. lastDirectionChange: currentTime,
  1289. directionChangeCount: 0,
  1290. oscillationAxis: 'none',
  1291. oscillationStartTime: 0
  1292. });
  1293. }
  1294. const posHistory = this.ballPositionHistory.get(ballId);
  1295. const dirHistory = this.ballDirectionHistory.get(ballId);
  1296. const oscillationData = this.ballOscillationDetection.get(ballId);
  1297. // 更新位置历史
  1298. posHistory.push(new Vec2(currentPos.x, currentPos.y));
  1299. if (posHistory.length > this.positionHistorySize) {
  1300. posHistory.shift();
  1301. }
  1302. // 更新方向历史
  1303. dirHistory.push(currentDirection.clone());
  1304. if (dirHistory.length > this.positionHistorySize) {
  1305. dirHistory.shift();
  1306. }
  1307. // 检测方向改变
  1308. if (dirHistory.length >= 2) {
  1309. const prevDirection = dirHistory[dirHistory.length - 2];
  1310. const dotProduct = Vec2.dot(prevDirection, currentDirection);
  1311. // 如果方向改变超过90度(点积小于0),认为是显著的方向改变
  1312. if (dotProduct < 0) {
  1313. oscillationData.directionChangeCount++;
  1314. oscillationData.lastDirectionChange = currentTime;
  1315. if (this.testMode) {
  1316. //console.log(`[防围困] 小球 ${ballId.substring(0, 8)} 方向改变,累计次数: ${oscillationData.directionChangeCount}`);
  1317. }
  1318. }
  1319. }
  1320. // 检测振荡模式
  1321. this.detectOscillationPattern(ballId, currentTime);
  1322. }
  1323. /**
  1324. * 检测振荡模式
  1325. */
  1326. private detectOscillationPattern(ballId: string, currentTime: number) {
  1327. const oscillationData = this.ballOscillationDetection.get(ballId);
  1328. const posHistory = this.ballPositionHistory.get(ballId);
  1329. if (!oscillationData || !posHistory || posHistory.length < 10) {
  1330. return;
  1331. }
  1332. // 检查是否在时间窗口内有足够的方向改变
  1333. const timeSinceLastChange = currentTime - oscillationData.lastDirectionChange;
  1334. if (timeSinceLastChange > this.oscillationTimeWindow) {
  1335. // 重置计数器
  1336. oscillationData.directionChangeCount = 0;
  1337. oscillationData.oscillationAxis = 'none';
  1338. return;
  1339. }
  1340. // 如果方向改变次数超过阈值,分析振荡轴向
  1341. if (oscillationData.directionChangeCount >= this.directionChangeThreshold) {
  1342. const axis = this.analyzeOscillationAxis(posHistory);
  1343. if (axis !== 'none' && oscillationData.oscillationAxis === 'none') {
  1344. // 开始振荡检测
  1345. oscillationData.oscillationAxis = axis;
  1346. oscillationData.oscillationStartTime = currentTime;
  1347. if (this.testMode) {
  1348. console.log(`[防围困] 检测到小球 ${ballId.substring(0, 8)} 在${axis === 'horizontal' ? '水平' : '垂直'}方向振荡`);
  1349. }
  1350. // 触发增强防围困机制
  1351. this.triggerEnhancedAntiTrap(ballId, axis);
  1352. }
  1353. }
  1354. }
  1355. /**
  1356. * 分析振荡轴向
  1357. */
  1358. private analyzeOscillationAxis(posHistory: Vec2[]): 'horizontal' | 'vertical' | 'none' {
  1359. if (posHistory.length < 10) {
  1360. return 'none';
  1361. }
  1362. const recentPositions = posHistory.slice(-10);
  1363. let minX = recentPositions[0].x, maxX = recentPositions[0].x;
  1364. let minY = recentPositions[0].y, maxY = recentPositions[0].y;
  1365. for (const pos of recentPositions) {
  1366. minX = Math.min(minX, pos.x);
  1367. maxX = Math.max(maxX, pos.x);
  1368. minY = Math.min(minY, pos.y);
  1369. maxY = Math.max(maxY, pos.y);
  1370. }
  1371. const xRange = maxX - minX;
  1372. const yRange = maxY - minY;
  1373. // 判断主要运动方向
  1374. if (xRange > this.oscillationDistanceThreshold && yRange < this.oscillationDistanceThreshold / 2) {
  1375. return 'horizontal';
  1376. } else if (yRange > this.oscillationDistanceThreshold && xRange < this.oscillationDistanceThreshold / 2) {
  1377. return 'vertical';
  1378. }
  1379. return 'none';
  1380. }
  1381. /**
  1382. * 触发增强防围困机制
  1383. */
  1384. private triggerEnhancedAntiTrap(ballId: string, oscillationAxis: 'horizontal' | 'vertical') {
  1385. const ball = this.activeBall;
  1386. if (!ball || !ball.isValid || ball.uuid !== ballId) {
  1387. return;
  1388. }
  1389. const rigidBody = ball.getComponent(RigidBody2D);
  1390. if (!rigidBody) {
  1391. return;
  1392. }
  1393. if (this.testMode) {
  1394. console.log(`[防围困] 触发增强防围困机制 - 小球 ${ballId.substring(0, 8)},轴向: ${oscillationAxis}`);
  1395. }
  1396. // 根据振荡轴向应用不同的策略
  1397. if (oscillationAxis === 'horizontal') {
  1398. // 水平振荡:给予垂直方向的随机冲量
  1399. const verticalImpulse = (Math.random() - 0.5) * this.baseSpeed * 0.8;
  1400. const newVelocity = new Vec2(rigidBody.linearVelocity.x * 0.3, verticalImpulse);
  1401. rigidBody.linearVelocity = newVelocity;
  1402. if (this.testMode) {
  1403. console.log(`[防围困] 水平振荡处理 - 应用垂直冲量: ${verticalImpulse.toFixed(2)}`);
  1404. }
  1405. } else if (oscillationAxis === 'vertical') {
  1406. // 垂直振荡:给予水平方向的随机冲量
  1407. const horizontalImpulse = (Math.random() - 0.5) * this.baseSpeed * 0.8;
  1408. const newVelocity = new Vec2(horizontalImpulse, rigidBody.linearVelocity.y * 0.3);
  1409. rigidBody.linearVelocity = newVelocity;
  1410. if (this.testMode) {
  1411. console.log(`[防围困] 垂直振荡处理 - 应用水平冲量: ${horizontalImpulse.toFixed(2)}`);
  1412. }
  1413. }
  1414. // 重置振荡检测数据
  1415. const oscillationData = this.ballOscillationDetection.get(ballId);
  1416. if (oscillationData) {
  1417. oscillationData.directionChangeCount = 0;
  1418. oscillationData.oscillationAxis = 'none';
  1419. }
  1420. }
  1421. /**
  1422. * 维持所有小球的恒定速度
  1423. */
  1424. private maintainAllBallsSpeed() {
  1425. // 维持主小球速度
  1426. if (this.activeBall && this.activeBall.isValid) {
  1427. this.maintainBallSpeed(this.activeBall);
  1428. }
  1429. // 维持额外小球的速度
  1430. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1431. if (gameArea) {
  1432. const additionalBalls = gameArea.children.filter(child =>
  1433. child.name === 'AdditionalBall' && child.isValid
  1434. );
  1435. for (const ball of additionalBalls) {
  1436. this.maintainBallSpeed(ball);
  1437. }
  1438. }
  1439. }
  1440. /**
  1441. * 维持单个小球的恒定速度
  1442. */
  1443. private maintainBallSpeed(ball: Node) {
  1444. const rigidBody = ball.getComponent(RigidBody2D);
  1445. if (!rigidBody) return;
  1446. // 获取当前速度
  1447. const currentVelocity = rigidBody.linearVelocity;
  1448. const speed = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
  1449. // 如果速度过低或过高,重新设置速度以维持恒定运动
  1450. if (speed < this.currentSpeed * 0.85 || speed > this.currentSpeed * 1.15) {
  1451. // 保持当前方向,但调整速度大小
  1452. if (speed > 0.1) {
  1453. const normalizedVelocity = currentVelocity.clone().normalize();
  1454. rigidBody.linearVelocity = new Vec2(
  1455. normalizedVelocity.x * this.currentSpeed,
  1456. normalizedVelocity.y * this.currentSpeed
  1457. );
  1458. } else {
  1459. // 如果速度几乎为0,给一个随机方向
  1460. const angle = Math.random() * Math.PI * 2;
  1461. rigidBody.linearVelocity = new Vec2(
  1462. Math.cos(angle) * this.currentSpeed,
  1463. Math.sin(angle) * this.currentSpeed
  1464. );
  1465. }
  1466. }
  1467. // 更新主小球的方向向量(用于其他逻辑)
  1468. if (ball === this.activeBall && speed > 1.0) {
  1469. this.direction.x = currentVelocity.x / speed;
  1470. this.direction.y = currentVelocity.y / speed;
  1471. }
  1472. }
  1473. // 调试方法:检查小球是否接近方块但没有触发物理碰撞
  1474. private debugCheckCounter = 0;
  1475. private debugCheckNearBlocks() {
  1476. this.debugCheckCounter++;
  1477. // 每60帧(约1秒)检查一次
  1478. if (this.debugCheckCounter % 60 !== 0) return;
  1479. const ballPos = this.activeBall.worldPosition;
  1480. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) return;
  1481. let nearestDistance = Infinity;
  1482. let nearestBlock = null;
  1483. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  1484. const block = this.placedBlocksContainer.children[i];
  1485. if (block.name.includes('Block') || block.getChildByName('B1')) {
  1486. const blockPos = block.worldPosition;
  1487. const distance = Math.sqrt(
  1488. Math.pow(ballPos.x - blockPos.x, 2) +
  1489. Math.pow(ballPos.y - blockPos.y, 2)
  1490. );
  1491. if (distance < nearestDistance) {
  1492. nearestDistance = distance;
  1493. nearestBlock = block;
  1494. }
  1495. }
  1496. }
  1497. if (nearestBlock && nearestDistance < 100) {
  1498. // 检查小球的碰撞体状态
  1499. const ballCollider = this.activeBall.getComponent(Collider2D);
  1500. if (ballCollider) {
  1501. if (ballCollider instanceof CircleCollider2D) {
  1502. // 小球碰撞半径检查
  1503. }
  1504. }
  1505. // 检查小球的刚体状态
  1506. const ballRigidBody = this.activeBall.getComponent(RigidBody2D);
  1507. if (ballRigidBody) {
  1508. // 刚体状态检查
  1509. }
  1510. // 检查最近的方块碰撞体
  1511. const blockCollider = nearestBlock.getComponent(Collider2D);
  1512. if (blockCollider) {
  1513. // 方块碰撞体检查
  1514. }
  1515. }
  1516. }
  1517. // 初始化方向
  1518. initializeDirection() {
  1519. // 测试模式:使用完全垂直或水平方向来测试防围困机制
  1520. if (this.testMode) {
  1521. // 四个基本方向:上、下、左、右
  1522. const directions = [
  1523. { x: 0, y: 1 }, // 向上
  1524. { x: 0, y: -1 }, // 向下
  1525. { x: 1, y: 0 }, // 向右
  1526. { x: -1, y: 0 } // 向左
  1527. ];
  1528. // 随机选择一个基本方向
  1529. const randomIndex = Math.floor(Math.random() * directions.length);
  1530. const selectedDirection = directions[randomIndex];
  1531. this.direction.x = selectedDirection.x;
  1532. this.direction.y = selectedDirection.y;
  1533. this.direction.normalize();
  1534. console.log(`[BallController] 测试模式 - 小球初始方向: ${randomIndex === 0 ? '向上' : randomIndex === 1 ? '向下' : randomIndex === 2 ? '向右' : '向左'}`);
  1535. } else {
  1536. // 原始随机方向模式
  1537. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  1538. this.direction.x = Math.cos(angle);
  1539. this.direction.y = Math.sin(angle);
  1540. this.direction.normalize();
  1541. }
  1542. // 设置初始速度
  1543. if (this.activeBall) {
  1544. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  1545. if (rigidBody) {
  1546. rigidBody.linearVelocity = new Vec2(
  1547. this.direction.x * this.currentSpeed,
  1548. this.direction.y * this.currentSpeed
  1549. );
  1550. }
  1551. }
  1552. }
  1553. // 初始化球的参数 - 公开方法,供GameManager调用
  1554. public initialize() {
  1555. this.calculateGameBounds();
  1556. this.createBall();
  1557. // 检查方块碰撞体(延迟执行,确保方块已放置)
  1558. this.scheduleOnce(() => {
  1559. this.checkBlockColliders();
  1560. }, 0.5);
  1561. }
  1562. // 启动小球 - 公开方法,在确定按钮点击后调用
  1563. public startBall() {
  1564. // 检查ballPrefab是否设置
  1565. if (!this.ballPrefab) {
  1566. console.error('[BallController] ballPrefab 未设置,无法创建小球');
  1567. return;
  1568. }
  1569. // 如果还没有初始化,先初始化
  1570. if (!this.initialized) {
  1571. this.initialize();
  1572. }
  1573. // 确保小球存在且有效
  1574. if (!this.activeBall || !this.activeBall.isValid) {
  1575. this.createBall();
  1576. }
  1577. // 检查小球是否成功创建
  1578. if (!this.activeBall) {
  1579. console.error('[BallController] 小球创建失败');
  1580. return;
  1581. }
  1582. // 重新定位小球,避免与方块重叠
  1583. this.positionBallRandomly();
  1584. // 确保物理组件设置正确
  1585. this.setupCollider();
  1586. // 初始化运动方向并开始运动
  1587. this.initializeDirection();
  1588. // 设置运动状态
  1589. this.ballStarted = true;
  1590. console.log('[BallController] 小球启动完成');
  1591. }
  1592. /**
  1593. * 暂停小球运动:记录当前速度并停止刚体
  1594. */
  1595. public pauseBall() {
  1596. if (this.isPaused) return;
  1597. this.isPaused = true;
  1598. this.ballStarted = false;
  1599. if (this.activeBall && this.activeBall.isValid) {
  1600. const rb = this.activeBall.getComponent(RigidBody2D);
  1601. if (rb) {
  1602. this.pausedVelocity = rb.linearVelocity.clone();
  1603. rb.linearVelocity = new Vec2(0, 0);
  1604. rb.sleep();
  1605. }
  1606. }
  1607. }
  1608. /**
  1609. * 恢复小球运动:恢复暂停前的速度
  1610. */
  1611. public resumeBall() {
  1612. if (!this.isPaused) return;
  1613. this.isPaused = false;
  1614. this.ballStarted = true;
  1615. console.log('恢复小球运动');
  1616. if (this.activeBall && this.activeBall.isValid) {
  1617. const rb = this.activeBall.getComponent(RigidBody2D);
  1618. if (rb) {
  1619. rb.wakeUp();
  1620. const hasPrevVelocity = this.pausedVelocity && (this.pausedVelocity.x !== 0 || this.pausedVelocity.y !== 0);
  1621. if (hasPrevVelocity) {
  1622. rb.linearVelocity = this.pausedVelocity.clone();
  1623. } else {
  1624. // 若没有记录速度,则重新初始化方向
  1625. this.initializeDirection();
  1626. }
  1627. }
  1628. }
  1629. }
  1630. /**
  1631. * 暂停所有小球运动:记录当前速度并停止所有刚体
  1632. */
  1633. public pauseAllBalls() {
  1634. if (this.isPaused) return;
  1635. this.isPaused = true;
  1636. this.ballStarted = false;
  1637. // 清空之前的暂停速度记录
  1638. this.allBallsPausedVelocities.clear();
  1639. // 暂停主球
  1640. if (this.activeBall && this.activeBall.isValid) {
  1641. const rb = this.activeBall.getComponent(RigidBody2D);
  1642. if (rb) {
  1643. this.allBallsPausedVelocities.set(this.activeBall, rb.linearVelocity.clone());
  1644. rb.linearVelocity = new Vec2(0, 0);
  1645. rb.sleep();
  1646. }
  1647. }
  1648. // 暂停所有额外球
  1649. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1650. if (gameArea) {
  1651. const additionalBalls = gameArea.children.filter(child =>
  1652. child.name === 'AdditionalBall' && child.isValid
  1653. );
  1654. for (const ball of additionalBalls) {
  1655. const rb = ball.getComponent(RigidBody2D);
  1656. if (rb) {
  1657. this.allBallsPausedVelocities.set(ball, rb.linearVelocity.clone());
  1658. rb.linearVelocity = new Vec2(0, 0);
  1659. rb.sleep();
  1660. }
  1661. }
  1662. }
  1663. console.log(`[BallController] 已暂停 ${this.allBallsPausedVelocities.size} 个小球`);
  1664. }
  1665. /**
  1666. * 恢复所有小球运动:恢复暂停前的速度
  1667. */
  1668. public resumeAllBalls() {
  1669. if (!this.isPaused) return;
  1670. this.isPaused = false;
  1671. this.ballStarted = true;
  1672. console.log(`[BallController] 恢复 ${this.allBallsPausedVelocities.size} 个小球运动`);
  1673. // 恢复所有记录的小球
  1674. for (const [ball, velocity] of this.allBallsPausedVelocities) {
  1675. if (ball && ball.isValid) {
  1676. const rb = ball.getComponent(RigidBody2D);
  1677. if (rb) {
  1678. rb.wakeUp();
  1679. const hasVelocity = velocity && (velocity.x !== 0 || velocity.y !== 0);
  1680. if (hasVelocity) {
  1681. rb.linearVelocity = velocity.clone();
  1682. } else {
  1683. // 如果没有记录速度,给一个默认方向
  1684. if (ball === this.activeBall) {
  1685. this.initializeDirection();
  1686. } else {
  1687. // 额外球给一个随机方向
  1688. const angle = Math.random() * Math.PI * 2;
  1689. const speed = this.currentSpeed;
  1690. rb.linearVelocity = new Vec2(Math.cos(angle) * speed, Math.sin(angle) * speed);
  1691. }
  1692. }
  1693. }
  1694. }
  1695. }
  1696. // 清空暂停速度记录
  1697. this.allBallsPausedVelocities.clear();
  1698. }
  1699. /**
  1700. * 从给定世界坐标发射子弹
  1701. */
  1702. private fireBulletAt(blockNode: Node, fireWorldPos: Vec3) {
  1703. // 检查方块节点是否有效
  1704. if (!blockNode || !blockNode.isValid) {
  1705. return;
  1706. }
  1707. // 检查子弹预制体是否存在
  1708. if (!this.bulletPrefab) {
  1709. console.warn(`[BallController] 子弹预制体未设置,无法发射`);
  1710. return;
  1711. }
  1712. // 查找方块中的武器节点
  1713. const weaponNode = this.findWeaponNode(blockNode);
  1714. if (!weaponNode) {
  1715. const blockName = blockNode && blockNode.isValid ? blockNode.name : 'unknown';
  1716. console.warn(`[BallController] 方块 ${blockName} 中未找到武器节点`);
  1717. }
  1718. // 传递武器节点和方块节点给createAndFireBullet方法
  1719. this.createAndFireBullet(fireWorldPos, weaponNode, blockNode);
  1720. }
  1721. /**
  1722. * 重置球控制器状态 - 游戏重置时调用
  1723. */
  1724. public resetBallController() {
  1725. console.log('[BallController] 重置球控制器状态');
  1726. // 停止球的运动
  1727. this.ballStarted = false;
  1728. this.isPaused = false;
  1729. // 清理暂停状态
  1730. this.pausedVelocity = new Vec2();
  1731. this.allBallsPausedVelocities.clear();
  1732. // 销毁当前活动的球
  1733. if (this.activeBall && this.activeBall.isValid) {
  1734. console.log('[BallController] 销毁当前活动的球');
  1735. this.activeBall.destroy();
  1736. }
  1737. this.activeBall = null;
  1738. // 销毁所有额外创建的球
  1739. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1740. if (gameArea) {
  1741. const additionalBalls = gameArea.children.filter(child =>
  1742. child.name === 'AdditionalBall' && child.isValid
  1743. );
  1744. for (const ball of additionalBalls) {
  1745. console.log('[BallController] 销毁额外球:', ball.name);
  1746. ball.destroy();
  1747. }
  1748. if (additionalBalls.length > 0) {
  1749. console.log(`[BallController] 已清理 ${additionalBalls.length} 个额外球`);
  1750. }
  1751. }
  1752. // 重置初始化状态
  1753. this.initialized = false;
  1754. // 清理冷却时间
  1755. this.blockFireCooldown.clear();
  1756. // 清理防围困状态数据
  1757. this.ballHitHistory.clear();
  1758. this.ballPhaseThrough.clear();
  1759. this.ballDeflectionAttempts.clear();
  1760. // 清理增强防围困机制的历史数据
  1761. this.ballPositionHistory.clear();
  1762. this.ballDirectionHistory.clear();
  1763. this.ballOscillationDetection.clear();
  1764. // 清理拖拽方块集合
  1765. this.draggingBlocks.clear();
  1766. // 重置球速
  1767. this.updateBallSpeed();
  1768. console.log('[BallController] 球控制器重置完成');
  1769. }
  1770. /**
  1771. * 清理过期的防围困状态
  1772. */
  1773. private cleanupExpiredAntiTrapStates() {
  1774. const currentTime = performance.now() / 1000;
  1775. // 清理过期的穿透状态
  1776. for (const [ballId, endTime] of this.ballPhaseThrough.entries()) {
  1777. if (currentTime >= endTime) {
  1778. this.ballPhaseThrough.delete(ballId);
  1779. }
  1780. }
  1781. // 检查并重置长时间未频繁撞击的球的偏移尝试次数
  1782. for (const [ballId, hitHistory] of this.ballHitHistory.entries()) {
  1783. // 如果撞击历史为空或最近一次撞击超过时间窗口的一半,重置偏移尝试次数
  1784. if (hitHistory.length === 0 ||
  1785. (hitHistory.length > 0 && currentTime - hitHistory[hitHistory.length - 1] > this.antiTrapTimeWindow / 2)) {
  1786. if (this.ballDeflectionAttempts.has(ballId)) {
  1787. this.ballDeflectionAttempts.set(ballId, 0);
  1788. }
  1789. }
  1790. }
  1791. }
  1792. /**
  1793. * 清理单个小球的防围困状态数据
  1794. * @param ballId 小球的唯一标识符
  1795. */
  1796. public cleanupBallAntiTrapState(ballId: string) {
  1797. this.ballHitHistory.delete(ballId);
  1798. this.ballPhaseThrough.delete(ballId);
  1799. this.ballDeflectionAttempts.delete(ballId);
  1800. console.log(`Cleaned up anti-trap state for ball ${ballId}`);
  1801. }
  1802. onDestroy() {
  1803. // 清理事件监听
  1804. const eventBus = EventBus.getInstance();
  1805. eventBus.off(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
  1806. eventBus.off(GameEvents.GAME_PAUSE_SKILL_SELECTION, this.onGamePauseSkillSelectionEvent, this);
  1807. eventBus.off(GameEvents.GAME_PAUSE_BLOCK_SELECTION, this.onGamePauseBlockSelectionEvent, this);
  1808. eventBus.off(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  1809. eventBus.off(GameEvents.RESET_BALL_CONTROLLER, this.onResetBallControllerEvent, this);
  1810. eventBus.off(GameEvents.BALL_CREATE, this.onBallCreateEvent, this);
  1811. eventBus.off(GameEvents.BALL_START, this.onBallStartEvent, this);
  1812. eventBus.off(GameEvents.BALL_CREATE_ADDITIONAL, this.onBallCreateAdditionalEvent, this);
  1813. eventBus.off(GameEvents.BALL_FIRE_BULLET, this.onBallFireBulletEvent, this);
  1814. eventBus.off(GameEvents.BLOCK_DRAG_START, this.onBlockDragStartEvent, this);
  1815. eventBus.off(GameEvents.BLOCK_DRAG_END, this.onBlockDragEndEvent, this);
  1816. // 清理物理事件监听器
  1817. const physics = PhysicsManager.getInstance()?.getSystem();
  1818. if (physics) {
  1819. physics.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  1820. }
  1821. // 清理防围困状态数据
  1822. this.ballHitHistory.clear();
  1823. this.ballPhaseThrough.clear();
  1824. this.ballDeflectionAttempts.clear();
  1825. }
  1826. private updateBallSpeed() {
  1827. const skillManager = PersistentSkillManager.getInstance();
  1828. if (skillManager) {
  1829. this.currentSpeed = skillManager.applyBallSpeedBonus(this.baseSpeed);
  1830. } else {
  1831. this.currentSpeed = this.baseSpeed;
  1832. }
  1833. }
  1834. // ==================== 小球位置检查机制 ====================
  1835. /**
  1836. * 获取所有活跃的小球
  1837. * @returns 返回所有活跃小球的数组
  1838. */
  1839. private getAllActiveBalls(): Node[] {
  1840. const balls: Node[] = [];
  1841. // 添加主小球
  1842. if (this.activeBall && this.activeBall.isValid) {
  1843. balls.push(this.activeBall);
  1844. }
  1845. // 查找所有额外小球
  1846. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1847. if (gameArea) {
  1848. // 遍历GameArea的所有子节点,查找小球
  1849. gameArea.children.forEach(child => {
  1850. if (child.name === 'AdditionalBall' && child.isValid) {
  1851. balls.push(child);
  1852. }
  1853. });
  1854. }
  1855. return balls;
  1856. }
  1857. /**
  1858. * 检查单个小球是否在游戏区域内
  1859. * @param ball 要检查的小球节点
  1860. * @returns 如果小球在游戏区域内返回true,否则返回false
  1861. */
  1862. private checkBallPosition(ball: Node): boolean {
  1863. if (!ball || !ball.isValid) {
  1864. return false;
  1865. }
  1866. // 获取小球的世界坐标
  1867. const worldPos = ball.getWorldPosition();
  1868. // 计算扩展后的边界(比游戏区域稍大,避免误判)
  1869. const extension = this.positionCheckBoundaryExtension;
  1870. const extendedBounds = {
  1871. left: this.gameBounds.left - extension,
  1872. right: this.gameBounds.right + extension,
  1873. top: this.gameBounds.top + extension,
  1874. bottom: this.gameBounds.bottom - extension
  1875. };
  1876. // 检查小球是否在扩展边界内
  1877. const isInBounds = worldPos.x >= extendedBounds.left &&
  1878. worldPos.x <= extendedBounds.right &&
  1879. worldPos.y >= extendedBounds.bottom &&
  1880. worldPos.y <= extendedBounds.top;
  1881. if (!isInBounds) {
  1882. console.warn(`[BallController] 小球 ${ball.name} 超出游戏区域:`, {
  1883. position: { x: worldPos.x, y: worldPos.y },
  1884. bounds: extendedBounds
  1885. });
  1886. }
  1887. return isInBounds;
  1888. }
  1889. /**
  1890. * 将小球重置回游戏区域
  1891. * @param ball 要重置的小球节点
  1892. */
  1893. private rescueBallToGameArea(ball: Node): void {
  1894. if (!ball || !ball.isValid) {
  1895. return;
  1896. }
  1897. console.log(`[BallController] 正在找回小球 ${ball.name}`);
  1898. // 使用与小球生成相同的安全位置设置逻辑
  1899. this.positionBallSafely(ball);
  1900. // 重新设置小球的运动方向和速度
  1901. const rigidBody = ball.getComponent(RigidBody2D);
  1902. if (rigidBody) {
  1903. // 随机新的运动方向
  1904. const angle = Math.random() * Math.PI * 2;
  1905. const direction = new Vec2(Math.cos(angle), Math.sin(angle)).normalize();
  1906. // 设置新的速度
  1907. rigidBody.linearVelocity = new Vec2(
  1908. direction.x * this.currentSpeed,
  1909. direction.y * this.currentSpeed
  1910. );
  1911. }
  1912. console.log(`[BallController] 小球 ${ball.name} 已重置到安全位置`);
  1913. }
  1914. /**
  1915. * 为小球设置安全位置(复用生成位置逻辑)
  1916. * @param ball 要设置位置的小球节点
  1917. */
  1918. private positionBallSafely(ball: Node): void {
  1919. if (!ball) return;
  1920. const transform = ball.getComponent(UITransform);
  1921. const ballRadius = transform ? transform.width / 2 : this.ballRadius;
  1922. // 计算可生成的范围(考虑小球半径,避免生成在边缘)
  1923. const minX = this.gameBounds.left + ballRadius + this.edgeOffset;
  1924. const maxX = this.gameBounds.right - ballRadius - this.edgeOffset;
  1925. const minY = this.gameBounds.bottom + ballRadius + this.edgeOffset;
  1926. const maxY = this.gameBounds.top - ballRadius - this.edgeOffset;
  1927. // 获取GameArea节点
  1928. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1929. if (!gameArea) {
  1930. return;
  1931. }
  1932. // 查找PlacedBlocks节点,它包含所有放置的方块
  1933. if (!this.placedBlocksContainer) {
  1934. this.setRandomPositionDefault(ball, minX, maxX, minY, maxY);
  1935. return;
  1936. }
  1937. if (!this.placedBlocksContainer.isValid) {
  1938. this.setRandomPositionDefault(ball, minX, maxX, minY, maxY);
  1939. return;
  1940. }
  1941. // 获取所有已放置的方块
  1942. const placedBlocks = [];
  1943. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  1944. const block = this.placedBlocksContainer.children[i];
  1945. // 检查是否是方块节点(通常以Block命名或有特定标识)
  1946. if (block.name.includes('Block') || block.getChildByName('B1')) {
  1947. placedBlocks.push(block);
  1948. }
  1949. }
  1950. // 如果没有方块,使用默认随机位置
  1951. if (placedBlocks.length === 0) {
  1952. this.setRandomPositionDefault(ball, minX, maxX, minY, maxY);
  1953. return;
  1954. }
  1955. // 尝试找到一个不与任何方块重叠的位置
  1956. let validPosition = false;
  1957. let attempts = 0;
  1958. const maxAttempts = this.maxAttempts;
  1959. let randomX, randomY;
  1960. while (!validPosition && attempts < maxAttempts) {
  1961. // 随机生成位置
  1962. randomX = Math.random() * (maxX - minX) + minX;
  1963. randomY = Math.random() * (maxY - minY) + minY;
  1964. // 检查是否与任何方块重叠
  1965. let overlapping = false;
  1966. for (const block of placedBlocks) {
  1967. // 获取方块的世界坐标
  1968. const blockWorldPos = block.worldPosition;
  1969. // 计算小球与方块的距离
  1970. const distance = Math.sqrt(
  1971. Math.pow(randomX - blockWorldPos.x, 2) +
  1972. Math.pow(randomY - blockWorldPos.y, 2)
  1973. );
  1974. // 获取方块的尺寸
  1975. const blockTransform = block.getComponent(UITransform);
  1976. const blockSize = blockTransform ?
  1977. Math.max(blockTransform.width, blockTransform.height) / 2 : this.safeDistance;
  1978. // 如果距离小于小球半径+方块尺寸的一半+安全距离,认为重叠
  1979. if (distance < ballRadius + blockSize + this.safeDistance) {
  1980. overlapping = true;
  1981. break;
  1982. }
  1983. }
  1984. // 如果没有重叠,找到了有效位置
  1985. if (!overlapping) {
  1986. validPosition = true;
  1987. }
  1988. attempts++;
  1989. }
  1990. // 如果找不到有效位置,使用默认位置(游戏区域底部中心)
  1991. if (!validPosition) {
  1992. randomX = (this.gameBounds.left + this.gameBounds.right) / 2;
  1993. randomY = this.gameBounds.bottom + ballRadius + this.safeDistance;
  1994. }
  1995. // 将世界坐标转换为相对于GameArea的本地坐标
  1996. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  1997. ball.position = localPos;
  1998. }
  1999. /**
  2000. * 设置小球默认位置
  2001. * @param ball 小球节点
  2002. * @param minX 最小X坐标
  2003. * @param maxX 最大X坐标
  2004. * @param minY 最小Y坐标
  2005. * @param maxY 最大Y坐标
  2006. */
  2007. private setRandomPositionDefault(ball: Node, minX: number, maxX: number, minY: number, maxY: number): void {
  2008. const gameArea = find('Canvas/GameLevelUI/GameArea');
  2009. if (!gameArea) return;
  2010. // 随机生成位置
  2011. const randomX = Math.random() * (maxX - minX) + minX;
  2012. const randomY = Math.random() * (maxY - minY) + minY;
  2013. // 将世界坐标转换为相对于GameArea的本地坐标
  2014. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  2015. ball.position = localPos;
  2016. }
  2017. /**
  2018. * 检查并找回所有超出游戏区域的小球
  2019. */
  2020. private checkAndRescueAllBalls(): void {
  2021. if (!this.enableBallPositionCheck) {
  2022. return;
  2023. }
  2024. const balls = this.getAllActiveBalls();
  2025. let rescuedCount = 0;
  2026. balls.forEach(ball => {
  2027. if (!this.checkBallPosition(ball)) {
  2028. this.rescueBallToGameArea(ball);
  2029. rescuedCount++;
  2030. }
  2031. });
  2032. if (rescuedCount > 0) {
  2033. console.log(`[BallController] 本次检查找回了 ${rescuedCount} 个小球`);
  2034. }
  2035. }
  2036. }