BallController.ts 92 KB

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