BallController.ts 92 KB

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