BallController.ts 87 KB

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