BallController.ts 83 KB

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