BallController.ts 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430
  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. */
  1083. private createAndFireBullet(firePosition: Vec3, weaponNode: Node | null) {
  1084. // 确保武器配置加载
  1085. WeaponBullet.loadWeaponsData().then(() => {
  1086. let finalConfig: WeaponConfig | null = null;
  1087. // 优先从武器节点的WeaponInfo组件获取配置
  1088. if (weaponNode && weaponNode.isValid) {
  1089. const weaponInfo = weaponNode.getComponent(WeaponInfo);
  1090. if (weaponInfo) {
  1091. finalConfig = weaponInfo.getWeaponConfig();
  1092. console.log(`[BallController] 从武器节点获取武器配置: ${finalConfig?.name || '未知'}`);
  1093. // 检查武器是否可以开火
  1094. if (!weaponInfo.canFire()) {
  1095. console.log(`[BallController] 武器 ${finalConfig?.name || '未知'} 冷却中,无法开火`);
  1096. return;
  1097. }
  1098. // 记录开火时间
  1099. weaponInfo.recordFireTime();
  1100. }
  1101. }
  1102. // 如果没有从武器节点获取到配置,使用默认配置
  1103. if (!finalConfig) {
  1104. const defaultWeaponId = 'pea_shooter';
  1105. finalConfig = WeaponBullet.getWeaponConfig(defaultWeaponId);
  1106. console.log(`[BallController] 使用默认武器配置: ${defaultWeaponId}`);
  1107. }
  1108. if (!finalConfig) {
  1109. console.warn(`[BallController] 无法获取武器配置,取消发射`);
  1110. return;
  1111. }
  1112. // 获取WeaponInfo组件(如果有的话)
  1113. let weaponInfoComponent: WeaponInfo | null = null;
  1114. if (weaponNode && weaponNode.isValid) {
  1115. weaponInfoComponent = weaponNode.getComponent(WeaponInfo);
  1116. }
  1117. // 获取BlockInfo组件(如果有的话)
  1118. // BlockInfo组件位于方块的Node子节点上,而不是Weapon子节点上
  1119. let blockInfoComponent: BlockInfo | null = null;
  1120. if (weaponNode && weaponNode.isValid && weaponNode.parent) {
  1121. // 从weaponNode的父节点(方块根节点)查找Node子节点
  1122. const blockRootNode = weaponNode.parent;
  1123. const nodeChild = blockRootNode.getChildByName('Node');
  1124. if (nodeChild) {
  1125. blockInfoComponent = nodeChild.getComponent(BlockInfo);
  1126. if (blockInfoComponent) {
  1127. console.log(`[BallController] 找到BlockInfo组件,稀有度等级: ${blockInfoComponent.rarity}, 稀有度名称: ${blockInfoComponent.getRarityName()}`);
  1128. } else {
  1129. console.log(`[BallController] Node子节点上未找到BlockInfo组件`);
  1130. }
  1131. } else {
  1132. console.log(`[BallController] 未找到Node子节点`);
  1133. }
  1134. // 如果还是没找到,尝试直接从weaponNode上获取(兼容旧结构)
  1135. if (!blockInfoComponent) {
  1136. blockInfoComponent = weaponNode.getComponent(BlockInfo);
  1137. if (blockInfoComponent) {
  1138. console.log(`[BallController] 从weaponNode上找到BlockInfo组件,稀有度等级: ${blockInfoComponent.rarity}, 稀有度名称: ${blockInfoComponent.getRarityName()}`);
  1139. } else {
  1140. console.log(`[BallController] 未找到BlockInfo组件,将使用JSON配置中的稀有度`);
  1141. }
  1142. }
  1143. }
  1144. // 创建子弹初始化数据
  1145. const initData: BulletInitData = {
  1146. weaponId: finalConfig.id,
  1147. firePosition: firePosition,
  1148. autoTarget: true,
  1149. weaponConfig: finalConfig,
  1150. weaponInfo: weaponInfoComponent,
  1151. blockInfo: blockInfoComponent
  1152. };
  1153. // 验证初始化数据
  1154. if (!WeaponBullet.validateInitData(initData)) {
  1155. console.warn(`[BallController] 子弹初始化数据验证失败`);
  1156. return;
  1157. }
  1158. // 查找GameArea(子弹统一添加到此节点)
  1159. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1160. if (!gameArea) {
  1161. console.warn(`[BallController] 未找到GameArea节点,无法发射子弹`);
  1162. return;
  1163. }
  1164. // === 根据武器配置选择合适的预制体 ===
  1165. const trailEffect = finalConfig.bulletConfig?.visual?.trailEffect;
  1166. // 尖胡萝卜特殊处理:使用PelletContainer预制体但激活Spine节点
  1167. const isSharpCarrot = finalConfig.id === 'sharp_carrot';
  1168. // 当trailEffect为true或者是尖胡萝卜时都使用容器预制体
  1169. const needsContainerPrefab = Boolean(trailEffect) || isSharpCarrot;
  1170. const prefabToUse: Prefab = (needsContainerPrefab && this.bulletContainerPrefab) ? this.bulletContainerPrefab : this.bulletPrefab;
  1171. if (!prefabToUse) {
  1172. console.warn(`[BallController] 没有可用的子弹预制体`);
  1173. return;
  1174. }
  1175. // 使用批量创建逻辑
  1176. console.log(`[BallController] 开始创建子弹 - 武器: ${finalConfig.name}, 预制体: ${prefabToUse ? prefabToUse.name : 'null'}`);
  1177. const bullets = WeaponBullet.createBullets(initData, prefabToUse as any);
  1178. console.log(`[BallController] WeaponBullet.createBullets 返回了 ${bullets.length} 个子弹`);
  1179. bullets.forEach((b, index) => {
  1180. console.log(`[BallController] 添加第 ${index + 1} 个子弹到场景 - 子弹节点: ${b ? b.name : 'null'}, 是否有效: ${b ? b.isValid : 'false'}`);
  1181. if (b && b.isValid) {
  1182. gameArea.addChild(b);
  1183. console.log(`[BallController] 子弹 ${index + 1} 成功添加到场景,世界坐标: ${b.worldPosition}`);
  1184. } else {
  1185. console.error(`[BallController] 子弹 ${index + 1} 无效,无法添加到场景`);
  1186. }
  1187. });
  1188. console.log(`[BallController] 成功发射 ${bullets.length} 发子弹,武器: ${finalConfig.name}`);
  1189. }).catch(error => {
  1190. console.error(`[BallController] 武器配置加载失败:`, error);
  1191. });
  1192. }
  1193. // 递归查找Weapon节点
  1194. private findWeaponNode(node: Node): Node | null {
  1195. // 检查节点是否有效
  1196. if (!node || !node.isValid) {
  1197. console.warn('[BallController] findWeaponNode: 传入的节点无效');
  1198. return null;
  1199. }
  1200. // 根据新的预制体结构,武器节点直接位于方块根节点下
  1201. // 首先检查当前节点是否有Weapon子节点
  1202. const weaponNode = node.getChildByName('Weapon');
  1203. if (weaponNode) {
  1204. return weaponNode;
  1205. }
  1206. // 如果当前节点没有Weapon子节点,检查父节点(可能传入的是Node子节点而不是预制体根节点)
  1207. if (node.parent) {
  1208. const parentWeaponNode = node.parent.getChildByName('Weapon');
  1209. if (parentWeaponNode) {
  1210. return parentWeaponNode;
  1211. }
  1212. }
  1213. // 最后使用递归方式查找(兼容其他可能的结构)
  1214. for (let i = 0; i < node.children.length; i++) {
  1215. const child = node.children[i];
  1216. const foundWeapon = this.findWeaponNode(child);
  1217. if (foundWeapon) {
  1218. return foundWeapon;
  1219. }
  1220. }
  1221. // 如果都没找到,返回null
  1222. console.warn('[BallController] 方块', node.name, '中未找到武器节点');
  1223. return null;
  1224. }
  1225. // 获取节点的完整路径
  1226. private getNodePath(node: Node): string {
  1227. let path = node.name;
  1228. let current = node;
  1229. while (current.parent) {
  1230. current = current.parent;
  1231. path = current.name + '/' + path;
  1232. }
  1233. return path;
  1234. }
  1235. private debugDragCounter = 0;
  1236. update(dt: number) {
  1237. // 只有当小球已启动时才执行运动逻辑
  1238. if (!this.ballStarted || !this.initialized) {
  1239. return;
  1240. }
  1241. // 维持所有小球的恒定速度
  1242. this.maintainAllBallsSpeed();
  1243. // 更新小球运动历史数据(用于检测振荡模式)
  1244. this.updateBallMovementHistory();
  1245. // 清理过期的防围困状态
  1246. this.cleanupExpiredAntiTrapStates();
  1247. // 定期检查小球位置,防止小球被挤出游戏区域
  1248. this.lastPositionCheckTime += dt;
  1249. if (this.lastPositionCheckTime >= this.positionCheckInterval) {
  1250. this.checkAndRescueAllBalls();
  1251. this.lastPositionCheckTime = 0;
  1252. }
  1253. // 定期检查小球是否接近方块但没有触发碰撞(调试用)
  1254. if (this.activeBall && this.activeBall.isValid) {
  1255. this.debugCheckNearBlocks();
  1256. }
  1257. // 定期调试拖拽状态(每5秒一次)
  1258. this.debugDragCounter += dt;
  1259. if (this.debugDragCounter >= 5.0 && this.draggingBlocks.size > 0) {
  1260. console.log('[BallController] 定期调试 - 当前拖拽状态:');
  1261. this.debugDraggingBlocks();
  1262. this.debugDragCounter = 0;
  1263. }
  1264. }
  1265. /**
  1266. * 更新小球运动历史数据(用于检测振荡模式)
  1267. */
  1268. private updateBallMovementHistory() {
  1269. if (!this.activeBall || !this.activeBall.isValid) {
  1270. return;
  1271. }
  1272. const ballId = this.activeBall.uuid;
  1273. const currentTime = Date.now() / 1000; // 转换为秒
  1274. const currentPos = this.activeBall.getWorldPosition();
  1275. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  1276. if (!rigidBody) {
  1277. return;
  1278. }
  1279. const currentVelocity = rigidBody.linearVelocity;
  1280. const currentDirection = new Vec2(currentVelocity.x, currentVelocity.y).normalize();
  1281. // 初始化历史记录
  1282. if (!this.ballPositionHistory.has(ballId)) {
  1283. this.ballPositionHistory.set(ballId, []);
  1284. this.ballDirectionHistory.set(ballId, []);
  1285. this.ballOscillationDetection.set(ballId, {
  1286. lastDirectionChange: currentTime,
  1287. directionChangeCount: 0,
  1288. oscillationAxis: 'none',
  1289. oscillationStartTime: 0
  1290. });
  1291. }
  1292. const posHistory = this.ballPositionHistory.get(ballId);
  1293. const dirHistory = this.ballDirectionHistory.get(ballId);
  1294. const oscillationData = this.ballOscillationDetection.get(ballId);
  1295. // 更新位置历史
  1296. posHistory.push(new Vec2(currentPos.x, currentPos.y));
  1297. if (posHistory.length > this.positionHistorySize) {
  1298. posHistory.shift();
  1299. }
  1300. // 更新方向历史
  1301. dirHistory.push(currentDirection.clone());
  1302. if (dirHistory.length > this.positionHistorySize) {
  1303. dirHistory.shift();
  1304. }
  1305. // 检测方向改变
  1306. if (dirHistory.length >= 2) {
  1307. const prevDirection = dirHistory[dirHistory.length - 2];
  1308. const dotProduct = Vec2.dot(prevDirection, currentDirection);
  1309. // 如果方向改变超过90度(点积小于0),认为是显著的方向改变
  1310. if (dotProduct < 0) {
  1311. oscillationData.directionChangeCount++;
  1312. oscillationData.lastDirectionChange = currentTime;
  1313. if (this.testMode) {
  1314. console.log(`[防围困] 小球 ${ballId.substring(0, 8)} 方向改变,累计次数: ${oscillationData.directionChangeCount}`);
  1315. }
  1316. }
  1317. }
  1318. // 检测振荡模式
  1319. this.detectOscillationPattern(ballId, currentTime);
  1320. }
  1321. /**
  1322. * 检测振荡模式
  1323. */
  1324. private detectOscillationPattern(ballId: string, currentTime: number) {
  1325. const oscillationData = this.ballOscillationDetection.get(ballId);
  1326. const posHistory = this.ballPositionHistory.get(ballId);
  1327. if (!oscillationData || !posHistory || posHistory.length < 10) {
  1328. return;
  1329. }
  1330. // 检查是否在时间窗口内有足够的方向改变
  1331. const timeSinceLastChange = currentTime - oscillationData.lastDirectionChange;
  1332. if (timeSinceLastChange > this.oscillationTimeWindow) {
  1333. // 重置计数器
  1334. oscillationData.directionChangeCount = 0;
  1335. oscillationData.oscillationAxis = 'none';
  1336. return;
  1337. }
  1338. // 如果方向改变次数超过阈值,分析振荡轴向
  1339. if (oscillationData.directionChangeCount >= this.directionChangeThreshold) {
  1340. const axis = this.analyzeOscillationAxis(posHistory);
  1341. if (axis !== 'none' && oscillationData.oscillationAxis === 'none') {
  1342. // 开始振荡检测
  1343. oscillationData.oscillationAxis = axis;
  1344. oscillationData.oscillationStartTime = currentTime;
  1345. if (this.testMode) {
  1346. console.log(`[防围困] 检测到小球 ${ballId.substring(0, 8)} 在${axis === 'horizontal' ? '水平' : '垂直'}方向振荡`);
  1347. }
  1348. // 触发增强防围困机制
  1349. this.triggerEnhancedAntiTrap(ballId, axis);
  1350. }
  1351. }
  1352. }
  1353. /**
  1354. * 分析振荡轴向
  1355. */
  1356. private analyzeOscillationAxis(posHistory: Vec2[]): 'horizontal' | 'vertical' | 'none' {
  1357. if (posHistory.length < 10) {
  1358. return 'none';
  1359. }
  1360. const recentPositions = posHistory.slice(-10);
  1361. let minX = recentPositions[0].x, maxX = recentPositions[0].x;
  1362. let minY = recentPositions[0].y, maxY = recentPositions[0].y;
  1363. for (const pos of recentPositions) {
  1364. minX = Math.min(minX, pos.x);
  1365. maxX = Math.max(maxX, pos.x);
  1366. minY = Math.min(minY, pos.y);
  1367. maxY = Math.max(maxY, pos.y);
  1368. }
  1369. const xRange = maxX - minX;
  1370. const yRange = maxY - minY;
  1371. // 判断主要运动方向
  1372. if (xRange > this.oscillationDistanceThreshold && yRange < this.oscillationDistanceThreshold / 2) {
  1373. return 'horizontal';
  1374. } else if (yRange > this.oscillationDistanceThreshold && xRange < this.oscillationDistanceThreshold / 2) {
  1375. return 'vertical';
  1376. }
  1377. return 'none';
  1378. }
  1379. /**
  1380. * 触发增强防围困机制
  1381. */
  1382. private triggerEnhancedAntiTrap(ballId: string, oscillationAxis: 'horizontal' | 'vertical') {
  1383. const ball = this.activeBall;
  1384. if (!ball || !ball.isValid || ball.uuid !== ballId) {
  1385. return;
  1386. }
  1387. const rigidBody = ball.getComponent(RigidBody2D);
  1388. if (!rigidBody) {
  1389. return;
  1390. }
  1391. if (this.testMode) {
  1392. console.log(`[防围困] 触发增强防围困机制 - 小球 ${ballId.substring(0, 8)},轴向: ${oscillationAxis}`);
  1393. }
  1394. // 根据振荡轴向应用不同的策略
  1395. if (oscillationAxis === 'horizontal') {
  1396. // 水平振荡:给予垂直方向的随机冲量
  1397. const verticalImpulse = (Math.random() - 0.5) * this.baseSpeed * 0.8;
  1398. const newVelocity = new Vec2(rigidBody.linearVelocity.x * 0.3, verticalImpulse);
  1399. rigidBody.linearVelocity = newVelocity;
  1400. if (this.testMode) {
  1401. console.log(`[防围困] 水平振荡处理 - 应用垂直冲量: ${verticalImpulse.toFixed(2)}`);
  1402. }
  1403. } else if (oscillationAxis === 'vertical') {
  1404. // 垂直振荡:给予水平方向的随机冲量
  1405. const horizontalImpulse = (Math.random() - 0.5) * this.baseSpeed * 0.8;
  1406. const newVelocity = new Vec2(horizontalImpulse, rigidBody.linearVelocity.y * 0.3);
  1407. rigidBody.linearVelocity = newVelocity;
  1408. if (this.testMode) {
  1409. console.log(`[防围困] 垂直振荡处理 - 应用水平冲量: ${horizontalImpulse.toFixed(2)}`);
  1410. }
  1411. }
  1412. // 重置振荡检测数据
  1413. const oscillationData = this.ballOscillationDetection.get(ballId);
  1414. if (oscillationData) {
  1415. oscillationData.directionChangeCount = 0;
  1416. oscillationData.oscillationAxis = 'none';
  1417. }
  1418. }
  1419. /**
  1420. * 维持所有小球的恒定速度
  1421. */
  1422. private maintainAllBallsSpeed() {
  1423. // 维持主小球速度
  1424. if (this.activeBall && this.activeBall.isValid) {
  1425. this.maintainBallSpeed(this.activeBall);
  1426. }
  1427. // 维持额外小球的速度
  1428. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1429. if (gameArea) {
  1430. const additionalBalls = gameArea.children.filter(child =>
  1431. child.name === 'AdditionalBall' && child.isValid
  1432. );
  1433. for (const ball of additionalBalls) {
  1434. this.maintainBallSpeed(ball);
  1435. }
  1436. }
  1437. }
  1438. /**
  1439. * 维持单个小球的恒定速度
  1440. */
  1441. private maintainBallSpeed(ball: Node) {
  1442. const rigidBody = ball.getComponent(RigidBody2D);
  1443. if (!rigidBody) return;
  1444. // 获取当前速度
  1445. const currentVelocity = rigidBody.linearVelocity;
  1446. const speed = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
  1447. // 如果速度过低或过高,重新设置速度以维持恒定运动
  1448. if (speed < this.currentSpeed * 0.85 || speed > this.currentSpeed * 1.15) {
  1449. // 保持当前方向,但调整速度大小
  1450. if (speed > 0.1) {
  1451. const normalizedVelocity = currentVelocity.clone().normalize();
  1452. rigidBody.linearVelocity = new Vec2(
  1453. normalizedVelocity.x * this.currentSpeed,
  1454. normalizedVelocity.y * this.currentSpeed
  1455. );
  1456. } else {
  1457. // 如果速度几乎为0,给一个随机方向
  1458. const angle = Math.random() * Math.PI * 2;
  1459. rigidBody.linearVelocity = new Vec2(
  1460. Math.cos(angle) * this.currentSpeed,
  1461. Math.sin(angle) * this.currentSpeed
  1462. );
  1463. }
  1464. }
  1465. // 更新主小球的方向向量(用于其他逻辑)
  1466. if (ball === this.activeBall && speed > 1.0) {
  1467. this.direction.x = currentVelocity.x / speed;
  1468. this.direction.y = currentVelocity.y / speed;
  1469. }
  1470. }
  1471. // 调试方法:检查小球是否接近方块但没有触发物理碰撞
  1472. private debugCheckCounter = 0;
  1473. private debugCheckNearBlocks() {
  1474. this.debugCheckCounter++;
  1475. // 每60帧(约1秒)检查一次
  1476. if (this.debugCheckCounter % 60 !== 0) return;
  1477. const ballPos = this.activeBall.worldPosition;
  1478. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) return;
  1479. let nearestDistance = Infinity;
  1480. let nearestBlock = null;
  1481. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  1482. const block = this.placedBlocksContainer.children[i];
  1483. if (block.name.includes('Block') || block.getChildByName('B1')) {
  1484. const blockPos = block.worldPosition;
  1485. const distance = Math.sqrt(
  1486. Math.pow(ballPos.x - blockPos.x, 2) +
  1487. Math.pow(ballPos.y - blockPos.y, 2)
  1488. );
  1489. if (distance < nearestDistance) {
  1490. nearestDistance = distance;
  1491. nearestBlock = block;
  1492. }
  1493. }
  1494. }
  1495. if (nearestBlock && nearestDistance < 100) {
  1496. // 检查小球的碰撞体状态
  1497. const ballCollider = this.activeBall.getComponent(Collider2D);
  1498. if (ballCollider) {
  1499. if (ballCollider instanceof CircleCollider2D) {
  1500. // 小球碰撞半径检查
  1501. }
  1502. }
  1503. // 检查小球的刚体状态
  1504. const ballRigidBody = this.activeBall.getComponent(RigidBody2D);
  1505. if (ballRigidBody) {
  1506. // 刚体状态检查
  1507. }
  1508. // 检查最近的方块碰撞体
  1509. const blockCollider = nearestBlock.getComponent(Collider2D);
  1510. if (blockCollider) {
  1511. // 方块碰撞体检查
  1512. }
  1513. }
  1514. }
  1515. // 初始化方向
  1516. initializeDirection() {
  1517. // 测试模式:使用完全垂直或水平方向来测试防围困机制
  1518. if (this.testMode) {
  1519. // 四个基本方向:上、下、左、右
  1520. const directions = [
  1521. { x: 0, y: 1 }, // 向上
  1522. { x: 0, y: -1 }, // 向下
  1523. { x: 1, y: 0 }, // 向右
  1524. { x: -1, y: 0 } // 向左
  1525. ];
  1526. // 随机选择一个基本方向
  1527. const randomIndex = Math.floor(Math.random() * directions.length);
  1528. const selectedDirection = directions[randomIndex];
  1529. this.direction.x = selectedDirection.x;
  1530. this.direction.y = selectedDirection.y;
  1531. this.direction.normalize();
  1532. console.log(`[BallController] 测试模式 - 小球初始方向: ${randomIndex === 0 ? '向上' : randomIndex === 1 ? '向下' : randomIndex === 2 ? '向右' : '向左'}`);
  1533. } else {
  1534. // 原始随机方向模式
  1535. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  1536. this.direction.x = Math.cos(angle);
  1537. this.direction.y = Math.sin(angle);
  1538. this.direction.normalize();
  1539. }
  1540. // 设置初始速度
  1541. if (this.activeBall) {
  1542. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  1543. if (rigidBody) {
  1544. rigidBody.linearVelocity = new Vec2(
  1545. this.direction.x * this.currentSpeed,
  1546. this.direction.y * this.currentSpeed
  1547. );
  1548. }
  1549. }
  1550. }
  1551. // 初始化球的参数 - 公开方法,供GameManager调用
  1552. public initialize() {
  1553. this.calculateGameBounds();
  1554. this.createBall();
  1555. // 检查方块碰撞体(延迟执行,确保方块已放置)
  1556. this.scheduleOnce(() => {
  1557. this.checkBlockColliders();
  1558. }, 0.5);
  1559. }
  1560. // 启动小球 - 公开方法,在确定按钮点击后调用
  1561. public startBall() {
  1562. // 检查ballPrefab是否设置
  1563. if (!this.ballPrefab) {
  1564. console.error('[BallController] ballPrefab 未设置,无法创建小球');
  1565. return;
  1566. }
  1567. // 如果还没有初始化,先初始化
  1568. if (!this.initialized) {
  1569. this.initialize();
  1570. }
  1571. // 确保小球存在且有效
  1572. if (!this.activeBall || !this.activeBall.isValid) {
  1573. this.createBall();
  1574. }
  1575. // 检查小球是否成功创建
  1576. if (!this.activeBall) {
  1577. console.error('[BallController] 小球创建失败');
  1578. return;
  1579. }
  1580. // 重新定位小球,避免与方块重叠
  1581. this.positionBallRandomly();
  1582. // 确保物理组件设置正确
  1583. this.setupCollider();
  1584. // 初始化运动方向并开始运动
  1585. this.initializeDirection();
  1586. // 设置运动状态
  1587. this.ballStarted = true;
  1588. console.log('[BallController] 小球启动完成');
  1589. }
  1590. /**
  1591. * 暂停小球运动:记录当前速度并停止刚体
  1592. */
  1593. public pauseBall() {
  1594. if (this.isPaused) return;
  1595. this.isPaused = true;
  1596. this.ballStarted = false;
  1597. if (this.activeBall && this.activeBall.isValid) {
  1598. const rb = this.activeBall.getComponent(RigidBody2D);
  1599. if (rb) {
  1600. this.pausedVelocity = rb.linearVelocity.clone();
  1601. rb.linearVelocity = new Vec2(0, 0);
  1602. rb.sleep();
  1603. }
  1604. }
  1605. }
  1606. /**
  1607. * 恢复小球运动:恢复暂停前的速度
  1608. */
  1609. public resumeBall() {
  1610. if (!this.isPaused) return;
  1611. this.isPaused = false;
  1612. this.ballStarted = true;
  1613. console.log('恢复小球运动');
  1614. if (this.activeBall && this.activeBall.isValid) {
  1615. const rb = this.activeBall.getComponent(RigidBody2D);
  1616. if (rb) {
  1617. rb.wakeUp();
  1618. const hasPrevVelocity = this.pausedVelocity && (this.pausedVelocity.x !== 0 || this.pausedVelocity.y !== 0);
  1619. if (hasPrevVelocity) {
  1620. rb.linearVelocity = this.pausedVelocity.clone();
  1621. } else {
  1622. // 若没有记录速度,则重新初始化方向
  1623. this.initializeDirection();
  1624. }
  1625. }
  1626. }
  1627. }
  1628. /**
  1629. * 暂停所有小球运动:记录当前速度并停止所有刚体
  1630. */
  1631. public pauseAllBalls() {
  1632. if (this.isPaused) return;
  1633. this.isPaused = true;
  1634. this.ballStarted = false;
  1635. // 清空之前的暂停速度记录
  1636. this.allBallsPausedVelocities.clear();
  1637. // 暂停主球
  1638. if (this.activeBall && this.activeBall.isValid) {
  1639. const rb = this.activeBall.getComponent(RigidBody2D);
  1640. if (rb) {
  1641. this.allBallsPausedVelocities.set(this.activeBall, rb.linearVelocity.clone());
  1642. rb.linearVelocity = new Vec2(0, 0);
  1643. rb.sleep();
  1644. }
  1645. }
  1646. // 暂停所有额外球
  1647. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1648. if (gameArea) {
  1649. const additionalBalls = gameArea.children.filter(child =>
  1650. child.name === 'AdditionalBall' && child.isValid
  1651. );
  1652. for (const ball of additionalBalls) {
  1653. const rb = ball.getComponent(RigidBody2D);
  1654. if (rb) {
  1655. this.allBallsPausedVelocities.set(ball, rb.linearVelocity.clone());
  1656. rb.linearVelocity = new Vec2(0, 0);
  1657. rb.sleep();
  1658. }
  1659. }
  1660. }
  1661. console.log(`[BallController] 已暂停 ${this.allBallsPausedVelocities.size} 个小球`);
  1662. }
  1663. /**
  1664. * 恢复所有小球运动:恢复暂停前的速度
  1665. */
  1666. public resumeAllBalls() {
  1667. if (!this.isPaused) return;
  1668. this.isPaused = false;
  1669. this.ballStarted = true;
  1670. console.log(`[BallController] 恢复 ${this.allBallsPausedVelocities.size} 个小球运动`);
  1671. // 恢复所有记录的小球
  1672. for (const [ball, velocity] of this.allBallsPausedVelocities) {
  1673. if (ball && ball.isValid) {
  1674. const rb = ball.getComponent(RigidBody2D);
  1675. if (rb) {
  1676. rb.wakeUp();
  1677. const hasVelocity = velocity && (velocity.x !== 0 || velocity.y !== 0);
  1678. if (hasVelocity) {
  1679. rb.linearVelocity = velocity.clone();
  1680. } else {
  1681. // 如果没有记录速度,给一个默认方向
  1682. if (ball === this.activeBall) {
  1683. this.initializeDirection();
  1684. } else {
  1685. // 额外球给一个随机方向
  1686. const angle = Math.random() * Math.PI * 2;
  1687. const speed = this.currentSpeed;
  1688. rb.linearVelocity = new Vec2(Math.cos(angle) * speed, Math.sin(angle) * speed);
  1689. }
  1690. }
  1691. }
  1692. }
  1693. }
  1694. // 清空暂停速度记录
  1695. this.allBallsPausedVelocities.clear();
  1696. }
  1697. /**
  1698. * 从给定世界坐标发射子弹
  1699. */
  1700. private fireBulletAt(blockNode: Node, fireWorldPos: Vec3) {
  1701. // 检查方块节点是否有效
  1702. if (!blockNode || !blockNode.isValid) {
  1703. return;
  1704. }
  1705. // 检查子弹预制体是否存在
  1706. if (!this.bulletPrefab) {
  1707. console.warn(`[BallController] 子弹预制体未设置,无法发射`);
  1708. return;
  1709. }
  1710. // 查找方块中的武器节点
  1711. const weaponNode = this.findWeaponNode(blockNode);
  1712. if (!weaponNode) {
  1713. const blockName = blockNode && blockNode.isValid ? blockNode.name : 'unknown';
  1714. console.warn(`[BallController] 方块 ${blockName} 中未找到武器节点`);
  1715. }
  1716. // 传递武器节点给createAndFireBullet方法
  1717. this.createAndFireBullet(fireWorldPos, weaponNode);
  1718. }
  1719. /**
  1720. * 重置球控制器状态 - 游戏重置时调用
  1721. */
  1722. public resetBallController() {
  1723. console.log('[BallController] 重置球控制器状态');
  1724. // 停止球的运动
  1725. this.ballStarted = false;
  1726. this.isPaused = false;
  1727. // 清理暂停状态
  1728. this.pausedVelocity = new Vec2();
  1729. this.allBallsPausedVelocities.clear();
  1730. // 销毁当前活动的球
  1731. if (this.activeBall && this.activeBall.isValid) {
  1732. console.log('[BallController] 销毁当前活动的球');
  1733. this.activeBall.destroy();
  1734. }
  1735. this.activeBall = null;
  1736. // 销毁所有额外创建的球
  1737. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1738. if (gameArea) {
  1739. const additionalBalls = gameArea.children.filter(child =>
  1740. child.name === 'AdditionalBall' && child.isValid
  1741. );
  1742. for (const ball of additionalBalls) {
  1743. console.log('[BallController] 销毁额外球:', ball.name);
  1744. ball.destroy();
  1745. }
  1746. if (additionalBalls.length > 0) {
  1747. console.log(`[BallController] 已清理 ${additionalBalls.length} 个额外球`);
  1748. }
  1749. }
  1750. // 重置初始化状态
  1751. this.initialized = false;
  1752. // 清理冷却时间
  1753. this.blockFireCooldown.clear();
  1754. // 清理防围困状态数据
  1755. this.ballHitHistory.clear();
  1756. this.ballPhaseThrough.clear();
  1757. this.ballDeflectionAttempts.clear();
  1758. // 清理增强防围困机制的历史数据
  1759. this.ballPositionHistory.clear();
  1760. this.ballDirectionHistory.clear();
  1761. this.ballOscillationDetection.clear();
  1762. // 清理拖拽方块集合
  1763. this.draggingBlocks.clear();
  1764. // 重置球速
  1765. this.updateBallSpeed();
  1766. console.log('[BallController] 球控制器重置完成');
  1767. }
  1768. /**
  1769. * 清理过期的防围困状态
  1770. */
  1771. private cleanupExpiredAntiTrapStates() {
  1772. const currentTime = performance.now() / 1000;
  1773. // 清理过期的穿透状态
  1774. for (const [ballId, endTime] of this.ballPhaseThrough.entries()) {
  1775. if (currentTime >= endTime) {
  1776. this.ballPhaseThrough.delete(ballId);
  1777. }
  1778. }
  1779. // 检查并重置长时间未频繁撞击的球的偏移尝试次数
  1780. for (const [ballId, hitHistory] of this.ballHitHistory.entries()) {
  1781. // 如果撞击历史为空或最近一次撞击超过时间窗口的一半,重置偏移尝试次数
  1782. if (hitHistory.length === 0 ||
  1783. (hitHistory.length > 0 && currentTime - hitHistory[hitHistory.length - 1] > this.antiTrapTimeWindow / 2)) {
  1784. if (this.ballDeflectionAttempts.has(ballId)) {
  1785. this.ballDeflectionAttempts.set(ballId, 0);
  1786. }
  1787. }
  1788. }
  1789. }
  1790. /**
  1791. * 清理单个小球的防围困状态数据
  1792. * @param ballId 小球的唯一标识符
  1793. */
  1794. public cleanupBallAntiTrapState(ballId: string) {
  1795. this.ballHitHistory.delete(ballId);
  1796. this.ballPhaseThrough.delete(ballId);
  1797. this.ballDeflectionAttempts.delete(ballId);
  1798. console.log(`Cleaned up anti-trap state for ball ${ballId}`);
  1799. }
  1800. onDestroy() {
  1801. // 清理事件监听
  1802. const eventBus = EventBus.getInstance();
  1803. eventBus.off(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
  1804. eventBus.off(GameEvents.GAME_PAUSE_SKILL_SELECTION, this.onGamePauseSkillSelectionEvent, this);
  1805. eventBus.off(GameEvents.GAME_PAUSE_BLOCK_SELECTION, this.onGamePauseBlockSelectionEvent, this);
  1806. eventBus.off(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  1807. eventBus.off(GameEvents.RESET_BALL_CONTROLLER, this.onResetBallControllerEvent, this);
  1808. eventBus.off(GameEvents.BALL_CREATE, this.onBallCreateEvent, this);
  1809. eventBus.off(GameEvents.BALL_START, this.onBallStartEvent, this);
  1810. eventBus.off(GameEvents.BALL_CREATE_ADDITIONAL, this.onBallCreateAdditionalEvent, this);
  1811. eventBus.off(GameEvents.BALL_FIRE_BULLET, this.onBallFireBulletEvent, this);
  1812. eventBus.off(GameEvents.BLOCK_DRAG_START, this.onBlockDragStartEvent, this);
  1813. eventBus.off(GameEvents.BLOCK_DRAG_END, this.onBlockDragEndEvent, this);
  1814. // 清理物理事件监听器
  1815. const physics = PhysicsManager.getInstance()?.getSystem();
  1816. if (physics) {
  1817. physics.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  1818. }
  1819. // 清理防围困状态数据
  1820. this.ballHitHistory.clear();
  1821. this.ballPhaseThrough.clear();
  1822. this.ballDeflectionAttempts.clear();
  1823. }
  1824. private updateBallSpeed() {
  1825. const skillManager = PersistentSkillManager.getInstance();
  1826. if (skillManager) {
  1827. this.currentSpeed = skillManager.applyBallSpeedBonus(this.baseSpeed);
  1828. } else {
  1829. this.currentSpeed = this.baseSpeed;
  1830. }
  1831. }
  1832. // ==================== 小球位置检查机制 ====================
  1833. /**
  1834. * 获取所有活跃的小球
  1835. * @returns 返回所有活跃小球的数组
  1836. */
  1837. private getAllActiveBalls(): Node[] {
  1838. const balls: Node[] = [];
  1839. // 添加主小球
  1840. if (this.activeBall && this.activeBall.isValid) {
  1841. balls.push(this.activeBall);
  1842. }
  1843. // 查找所有额外小球
  1844. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1845. if (gameArea) {
  1846. // 遍历GameArea的所有子节点,查找小球
  1847. gameArea.children.forEach(child => {
  1848. if (child.name === 'AdditionalBall' && child.isValid) {
  1849. balls.push(child);
  1850. }
  1851. });
  1852. }
  1853. return balls;
  1854. }
  1855. /**
  1856. * 检查单个小球是否在游戏区域内
  1857. * @param ball 要检查的小球节点
  1858. * @returns 如果小球在游戏区域内返回true,否则返回false
  1859. */
  1860. private checkBallPosition(ball: Node): boolean {
  1861. if (!ball || !ball.isValid) {
  1862. return false;
  1863. }
  1864. // 获取小球的世界坐标
  1865. const worldPos = ball.getWorldPosition();
  1866. // 计算扩展后的边界(比游戏区域稍大,避免误判)
  1867. const extension = this.positionCheckBoundaryExtension;
  1868. const extendedBounds = {
  1869. left: this.gameBounds.left - extension,
  1870. right: this.gameBounds.right + extension,
  1871. top: this.gameBounds.top + extension,
  1872. bottom: this.gameBounds.bottom - extension
  1873. };
  1874. // 检查小球是否在扩展边界内
  1875. const isInBounds = worldPos.x >= extendedBounds.left &&
  1876. worldPos.x <= extendedBounds.right &&
  1877. worldPos.y >= extendedBounds.bottom &&
  1878. worldPos.y <= extendedBounds.top;
  1879. if (!isInBounds) {
  1880. console.warn(`[BallController] 小球 ${ball.name} 超出游戏区域:`, {
  1881. position: { x: worldPos.x, y: worldPos.y },
  1882. bounds: extendedBounds
  1883. });
  1884. }
  1885. return isInBounds;
  1886. }
  1887. /**
  1888. * 将小球重置回游戏区域
  1889. * @param ball 要重置的小球节点
  1890. */
  1891. private rescueBallToGameArea(ball: Node): void {
  1892. if (!ball || !ball.isValid) {
  1893. return;
  1894. }
  1895. console.log(`[BallController] 正在找回小球 ${ball.name}`);
  1896. // 使用与小球生成相同的安全位置设置逻辑
  1897. this.positionBallSafely(ball);
  1898. // 重新设置小球的运动方向和速度
  1899. const rigidBody = ball.getComponent(RigidBody2D);
  1900. if (rigidBody) {
  1901. // 随机新的运动方向
  1902. const angle = Math.random() * Math.PI * 2;
  1903. const direction = new Vec2(Math.cos(angle), Math.sin(angle)).normalize();
  1904. // 设置新的速度
  1905. rigidBody.linearVelocity = new Vec2(
  1906. direction.x * this.currentSpeed,
  1907. direction.y * this.currentSpeed
  1908. );
  1909. }
  1910. console.log(`[BallController] 小球 ${ball.name} 已重置到安全位置`);
  1911. }
  1912. /**
  1913. * 为小球设置安全位置(复用生成位置逻辑)
  1914. * @param ball 要设置位置的小球节点
  1915. */
  1916. private positionBallSafely(ball: Node): void {
  1917. if (!ball) return;
  1918. const transform = ball.getComponent(UITransform);
  1919. const ballRadius = transform ? transform.width / 2 : this.ballRadius;
  1920. // 计算可生成的范围(考虑小球半径,避免生成在边缘)
  1921. const minX = this.gameBounds.left + ballRadius + this.edgeOffset;
  1922. const maxX = this.gameBounds.right - ballRadius - this.edgeOffset;
  1923. const minY = this.gameBounds.bottom + ballRadius + this.edgeOffset;
  1924. const maxY = this.gameBounds.top - ballRadius - this.edgeOffset;
  1925. // 获取GameArea节点
  1926. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1927. if (!gameArea) {
  1928. return;
  1929. }
  1930. // 查找PlacedBlocks节点,它包含所有放置的方块
  1931. if (!this.placedBlocksContainer) {
  1932. this.setRandomPositionDefault(ball, minX, maxX, minY, maxY);
  1933. return;
  1934. }
  1935. if (!this.placedBlocksContainer.isValid) {
  1936. this.setRandomPositionDefault(ball, minX, maxX, minY, maxY);
  1937. return;
  1938. }
  1939. // 获取所有已放置的方块
  1940. const placedBlocks = [];
  1941. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  1942. const block = this.placedBlocksContainer.children[i];
  1943. // 检查是否是方块节点(通常以Block命名或有特定标识)
  1944. if (block.name.includes('Block') || block.getChildByName('B1')) {
  1945. placedBlocks.push(block);
  1946. }
  1947. }
  1948. // 如果没有方块,使用默认随机位置
  1949. if (placedBlocks.length === 0) {
  1950. this.setRandomPositionDefault(ball, minX, maxX, minY, maxY);
  1951. return;
  1952. }
  1953. // 尝试找到一个不与任何方块重叠的位置
  1954. let validPosition = false;
  1955. let attempts = 0;
  1956. const maxAttempts = this.maxAttempts;
  1957. let randomX, randomY;
  1958. while (!validPosition && attempts < maxAttempts) {
  1959. // 随机生成位置
  1960. randomX = Math.random() * (maxX - minX) + minX;
  1961. randomY = Math.random() * (maxY - minY) + minY;
  1962. // 检查是否与任何方块重叠
  1963. let overlapping = false;
  1964. for (const block of placedBlocks) {
  1965. // 获取方块的世界坐标
  1966. const blockWorldPos = block.worldPosition;
  1967. // 计算小球与方块的距离
  1968. const distance = Math.sqrt(
  1969. Math.pow(randomX - blockWorldPos.x, 2) +
  1970. Math.pow(randomY - blockWorldPos.y, 2)
  1971. );
  1972. // 获取方块的尺寸
  1973. const blockTransform = block.getComponent(UITransform);
  1974. const blockSize = blockTransform ?
  1975. Math.max(blockTransform.width, blockTransform.height) / 2 : this.safeDistance;
  1976. // 如果距离小于小球半径+方块尺寸的一半+安全距离,认为重叠
  1977. if (distance < ballRadius + blockSize + this.safeDistance) {
  1978. overlapping = true;
  1979. break;
  1980. }
  1981. }
  1982. // 如果没有重叠,找到了有效位置
  1983. if (!overlapping) {
  1984. validPosition = true;
  1985. }
  1986. attempts++;
  1987. }
  1988. // 如果找不到有效位置,使用默认位置(游戏区域底部中心)
  1989. if (!validPosition) {
  1990. randomX = (this.gameBounds.left + this.gameBounds.right) / 2;
  1991. randomY = this.gameBounds.bottom + ballRadius + this.safeDistance;
  1992. }
  1993. // 将世界坐标转换为相对于GameArea的本地坐标
  1994. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  1995. ball.position = localPos;
  1996. }
  1997. /**
  1998. * 设置小球默认位置
  1999. * @param ball 小球节点
  2000. * @param minX 最小X坐标
  2001. * @param maxX 最大X坐标
  2002. * @param minY 最小Y坐标
  2003. * @param maxY 最大Y坐标
  2004. */
  2005. private setRandomPositionDefault(ball: Node, minX: number, maxX: number, minY: number, maxY: number): void {
  2006. const gameArea = find('Canvas/GameLevelUI/GameArea');
  2007. if (!gameArea) return;
  2008. // 随机生成位置
  2009. const randomX = Math.random() * (maxX - minX) + minX;
  2010. const randomY = Math.random() * (maxY - minY) + minY;
  2011. // 将世界坐标转换为相对于GameArea的本地坐标
  2012. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  2013. ball.position = localPos;
  2014. }
  2015. /**
  2016. * 检查并找回所有超出游戏区域的小球
  2017. */
  2018. private checkAndRescueAllBalls(): void {
  2019. if (!this.enableBallPositionCheck) {
  2020. return;
  2021. }
  2022. const balls = this.getAllActiveBalls();
  2023. let rescuedCount = 0;
  2024. balls.forEach(ball => {
  2025. if (!this.checkBallPosition(ball)) {
  2026. this.rescueBallToGameArea(ball);
  2027. rescuedCount++;
  2028. }
  2029. });
  2030. if (rescuedCount > 0) {
  2031. console.log(`[BallController] 本次检查找回了 ${rescuedCount} 个小球`);
  2032. }
  2033. }
  2034. }