BallController.ts 78 KB

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