BallController.ts 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  1. import { _decorator, Component, Node, Vec2, Vec3, UITransform, Collider2D, Contact2DType, IPhysics2DContact, RigidBody2D, Prefab, instantiate, find, CircleCollider2D } from 'cc';
  2. import { PhysicsManager } from '../Core/PhysicsManager';
  3. import { WeaponBullet, BulletInitData, WeaponConfig } from './WeaponBullet';
  4. import EventBus, { GameEvents } from '../Core/EventBus';
  5. import { PersistentSkillManager } from '../FourUI/SkillSystem/PersistentSkillManager';
  6. import { BallAni } from '../Animations/BallAni';
  7. const { ccclass, property } = _decorator;
  8. @ccclass('BallController')
  9. export class BallController extends Component {
  10. // 球的预制体
  11. @property({
  12. type: Prefab,
  13. tooltip: '拖拽Ball预制体到这里'
  14. })
  15. public ballPrefab: Prefab = null;
  16. // 已放置方块容器节点
  17. @property({
  18. type: Node,
  19. tooltip: '拖拽PlacedBlocks节点到这里(Canvas/GameLevelUI/PlacedBlocks)'
  20. })
  21. public placedBlocksContainer: Node = null;
  22. // 球的移动速度
  23. @property
  24. public baseSpeed: number = 60;
  25. public currentSpeed: number = 60;
  26. // 反弹随机偏移最大角度(弧度)
  27. @property
  28. public maxReflectionRandomness: number = 0.2;
  29. // 当前活动的球
  30. private activeBall: Node = null;
  31. // 球的方向向量
  32. private direction: Vec2 = new Vec2();
  33. // GameArea区域边界
  34. private gameBounds = {
  35. left: 0,
  36. right: 0,
  37. top: 0,
  38. bottom: 0
  39. };
  40. // 球的半径
  41. private radius: number = 0;
  42. // 是否已初始化
  43. private initialized: boolean = false;
  44. // 子弹预制体
  45. @property({
  46. type: Prefab,
  47. tooltip: '拖拽子弹预制体到这里'
  48. })
  49. public bulletPrefab: Prefab = null;
  50. // 小球是否已开始运动
  51. private ballStarted: boolean = false;
  52. // 小球暂停时记录的速度
  53. private pausedVelocity: Vec2 = new Vec2();
  54. // 标记是否处于暂停状态
  55. private isPaused: boolean = false;
  56. // 在类字段区添加
  57. private blockFireCooldown: Map<string, number> = new Map();
  58. private FIRE_COOLDOWN = 0.05;
  59. // 防围困机制配置
  60. @property({
  61. tooltip: '防围困检测时间窗口(秒)'
  62. })
  63. public antiTrapTimeWindow: number = 5.0;
  64. @property({
  65. tooltip: '防围困撞击次数阈值'
  66. })
  67. public antiTrapHitThreshold: number = 5;
  68. @property({
  69. tooltip: '偏移尝试次数阈值(达到后才使用穿透)'
  70. })
  71. public deflectionAttemptThreshold: number = 3;
  72. @property({
  73. tooltip: '防围困偏移强度倍数'
  74. })
  75. public antiTrapDeflectionMultiplier: number = 3.0;
  76. // 防围困机制状态
  77. private ballHitHistory: Map<string, number[]> = new Map(); // 记录每个球的撞击时间历史
  78. private ballPhaseThrough: Map<string, number> = new Map(); // 记录每个球的穿透结束时间
  79. private ballDeflectionAttempts: Map<string, number> = new Map(); // 记录每个球的偏移尝试次数
  80. // 带尾部特效的子弹容器预制体
  81. @property({
  82. type: Prefab,
  83. tooltip: '拖拽带尾部特效的子弹容器预制体到这里(例如 PelletContainer)'
  84. })
  85. public bulletContainerPrefab: Prefab = null;
  86. start() {
  87. // 如果没有指定placedBlocksContainer,尝试找到它
  88. if (!this.placedBlocksContainer) {
  89. this.placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks');
  90. if (!this.placedBlocksContainer) {
  91. // 找不到PlacedBlocks节点,某些功能可能无法正常工作
  92. }
  93. }
  94. // 只进行初始设置,不创建小球
  95. this.calculateGameBounds();
  96. // 监听游戏事件
  97. this.setupEventListeners();
  98. // 监听球速技能变化并更新球速
  99. this.updateBallSpeed();
  100. }
  101. /**
  102. * 设置事件监听器
  103. */
  104. private setupEventListeners() {
  105. const eventBus = EventBus.getInstance();
  106. // 监听暂停事件
  107. eventBus.on(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
  108. // 监听恢复事件
  109. eventBus.on(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  110. // 监听重置球控制器事件
  111. eventBus.on(GameEvents.RESET_BALL_CONTROLLER, this.onResetBallControllerEvent, this);
  112. // 监听球创建事件
  113. eventBus.on(GameEvents.BALL_CREATE, this.onBallCreateEvent, this);
  114. // 监听球启动事件
  115. eventBus.on(GameEvents.BALL_START, this.onBallStartEvent, this);
  116. // 监听创建额外球事件
  117. eventBus.on(GameEvents.BALL_CREATE_ADDITIONAL, this.onBallCreateAdditionalEvent, this);
  118. }
  119. /**
  120. * 处理游戏暂停事件
  121. */
  122. private onGamePauseEvent() {
  123. console.log('[BallController] 接收到游戏暂停事件');
  124. // 根据需求,暂停时小球继续运动但不发射子弹
  125. // 子弹发射的控制已经通过GamePause.isBulletFireEnabled()实现
  126. // 这里可以添加其他暂停相关的逻辑
  127. }
  128. /**
  129. * 处理游戏恢复事件
  130. */
  131. private onGameResumeEvent() {
  132. console.log('[BallController] 接收到游戏恢复事件');
  133. // 恢复时重新启用子弹发射
  134. // 子弹发射的控制已经通过GamePause.isBulletFireEnabled()实现
  135. // 这里可以添加其他恢复相关的逻辑
  136. }
  137. /**
  138. * 处理重置球控制器事件
  139. */
  140. private onResetBallControllerEvent() {
  141. console.log('[BallController] 接收到重置球控制器事件');
  142. this.resetBallController();
  143. }
  144. /**
  145. * 处理球创建事件
  146. */
  147. private onBallCreateEvent() {
  148. console.log('[BallController] 接收到球创建事件');
  149. this.createBall();
  150. }
  151. /**
  152. * 处理球启动事件
  153. */
  154. private onBallStartEvent() {
  155. console.log('[BallController] 接收到球启动事件');
  156. this.startBall();
  157. }
  158. /**
  159. * 处理创建额外球事件
  160. */
  161. private onBallCreateAdditionalEvent() {
  162. console.log('[BallController] 接收到创建额外球事件');
  163. this.createAdditionalBall();
  164. }
  165. // 计算游戏边界(使用GameArea节点)
  166. calculateGameBounds() {
  167. // 获取GameArea节点
  168. const gameArea = find('Canvas/GameLevelUI/GameArea');
  169. if (!gameArea) {
  170. return;
  171. }
  172. const gameAreaUI = gameArea.getComponent(UITransform);
  173. if (!gameAreaUI) {
  174. return;
  175. }
  176. // 获取GameArea的尺寸
  177. const areaWidth = gameAreaUI.width;
  178. const areaHeight = gameAreaUI.height;
  179. // 获取GameArea的世界坐标位置
  180. const worldPos = gameArea.worldPosition;
  181. // 计算GameArea的世界坐标边界
  182. this.gameBounds.left = worldPos.x - areaWidth / 2;
  183. this.gameBounds.right = worldPos.x + areaWidth / 2;
  184. this.gameBounds.bottom = worldPos.y - areaHeight / 2;
  185. this.gameBounds.top = worldPos.y + areaHeight / 2;
  186. }
  187. // 创建小球
  188. createBall() {
  189. if (!this.ballPrefab) {
  190. console.error('[BallController] ballPrefab 未设置,无法创建小球');
  191. return;
  192. }
  193. // 实例化小球
  194. this.activeBall = instantiate(this.ballPrefab);
  195. if (!this.activeBall) {
  196. console.error('[BallController] 小球实例化失败');
  197. return;
  198. }
  199. // 将小球添加到GameArea中
  200. const gameArea = find('Canvas/GameLevelUI/GameArea');
  201. if (gameArea) {
  202. gameArea.addChild(this.activeBall);
  203. } else {
  204. console.warn('[BallController] 未找到GameArea,将小球添加到当前节点');
  205. this.node.addChild(this.activeBall);
  206. }
  207. // 随机位置小球
  208. this.positionBallRandomly();
  209. // 设置球的半径
  210. const transform = this.activeBall.getComponent(UITransform);
  211. if (transform) {
  212. this.radius = transform.width / 2;
  213. } else {
  214. this.radius = 25; // 默认半径
  215. }
  216. // 确保有碰撞组件
  217. this.setupCollider();
  218. // 注意:不在这里初始化方向,等待 startBall() 调用
  219. this.initialized = true;
  220. }
  221. // 创建额外的小球(不替换现有的小球)
  222. public createAdditionalBall() {
  223. if (!this.ballPrefab) {
  224. console.error('无法创建额外小球:ballPrefab 未设置');
  225. return;
  226. }
  227. // 实例化新的小球
  228. const newBall = instantiate(this.ballPrefab);
  229. newBall.name = 'AdditionalBall';
  230. // 将小球添加到GameArea中
  231. const gameArea = find('Canvas/GameLevelUI/GameArea');
  232. if (gameArea) {
  233. gameArea.addChild(newBall);
  234. } else {
  235. this.node.addChild(newBall);
  236. }
  237. // 随机位置小球
  238. this.positionAdditionalBall(newBall);
  239. // 设置球的碰撞组件
  240. this.setupBallCollider(newBall);
  241. // 设置初始方向和速度
  242. this.initializeBallDirection(newBall);
  243. console.log('创建了额外的小球');
  244. return newBall;
  245. }
  246. // 为额外小球设置随机位置
  247. private positionAdditionalBall(ball: Node) {
  248. if (!ball) return;
  249. const transform = ball.getComponent(UITransform);
  250. const ballRadius = transform ? transform.width / 2 : 25;
  251. // 计算可生成的范围(考虑小球半径,避免生成在边缘)
  252. const minX = this.gameBounds.left + ballRadius + 20;
  253. const maxX = this.gameBounds.right - ballRadius - 20;
  254. const minY = this.gameBounds.bottom + ballRadius + 20;
  255. const maxY = this.gameBounds.top - ballRadius - 20;
  256. // 获取GameArea节点
  257. const gameArea = find('Canvas/GameLevelUI/GameArea');
  258. if (!gameArea) {
  259. return;
  260. }
  261. // 随机生成位置
  262. const randomX = Math.random() * (maxX - minX) + minX;
  263. const randomY = Math.random() * (maxY - minY) + minY;
  264. // 将世界坐标转换为相对于GameArea的本地坐标
  265. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  266. ball.position = localPos;
  267. }
  268. // 为额外小球设置碰撞组件
  269. private setupBallCollider(ball: Node) {
  270. // 确保有碰撞组件
  271. let collider = ball.getComponent(CircleCollider2D);
  272. if (!collider) {
  273. collider = ball.addComponent(CircleCollider2D);
  274. }
  275. // 设置碰撞属性
  276. collider.radius = ball.getComponent(UITransform)?.width / 2 || 25;
  277. collider.group = 1; // 设置为球的碰撞组
  278. collider.tag = 1; // 小球标签
  279. collider.sensor = false;
  280. collider.friction = 0; // 无摩擦
  281. collider.restitution = 1; // 完全弹性碰撞
  282. // 添加刚体组件
  283. let rigidBody = ball.getComponent(RigidBody2D);
  284. if (!rigidBody) {
  285. rigidBody = ball.addComponent(RigidBody2D);
  286. }
  287. // 设置刚体属性
  288. rigidBody.type = 2; // 2 = 动态刚体
  289. rigidBody.allowSleep = false;
  290. rigidBody.gravityScale = 0;
  291. rigidBody.linearDamping = 0; // 无线性阻尼,保持速度不衰减
  292. rigidBody.angularDamping = 0; // 无角阻尼
  293. rigidBody.fixedRotation = true;
  294. rigidBody.enabledContactListener = true; // 启用碰撞监听
  295. // 注意:不需要为每个小球单独添加碰撞回调,
  296. // 因为我们使用的是全局物理系统回调
  297. }
  298. // 为额外小球初始化方向和速度
  299. private initializeBallDirection(ball: Node) {
  300. // 随机初始方向
  301. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  302. const direction = new Vec2(Math.cos(angle), Math.sin(angle)).normalize();
  303. // 设置初始速度
  304. const rigidBody = ball.getComponent(RigidBody2D);
  305. if (rigidBody) {
  306. rigidBody.linearVelocity = new Vec2(
  307. direction.x * this.currentSpeed,
  308. direction.y * this.currentSpeed
  309. );
  310. }
  311. }
  312. // 检查所有已放置方块的碰撞体组件
  313. private checkBlockColliders() {
  314. if (!this.placedBlocksContainer) {
  315. return;
  316. }
  317. if (!this.placedBlocksContainer.isValid) {
  318. return;
  319. }
  320. const blocks = [];
  321. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  322. const block = this.placedBlocksContainer.children[i];
  323. if (block.name.includes('Block') || block.getChildByName('B1')) {
  324. blocks.push(block);
  325. }
  326. }
  327. let fixedCount = 0;
  328. for (let i = 0; i < blocks.length; i++) {
  329. const block = blocks[i];
  330. // 检查方块本身的碰撞体
  331. const blockCollider = block.getComponent(Collider2D);
  332. if (blockCollider) {
  333. // 🔧 自动修复碰撞组设置
  334. if (blockCollider.group !== 2) {
  335. blockCollider.group = 2; // 设置为Block组
  336. fixedCount++;
  337. }
  338. // 确保不是传感器
  339. if (blockCollider.sensor) {
  340. blockCollider.sensor = false;
  341. }
  342. }
  343. // 检查B1子节点的碰撞体
  344. const b1Node = block.getChildByName('B1');
  345. if (b1Node) {
  346. const b1Collider = b1Node.getComponent(Collider2D);
  347. if (b1Collider) {
  348. // 🔧 修复B1子节点的碰撞设置
  349. if (b1Collider.group !== 2) {
  350. b1Collider.group = 2; // 设置为Block组
  351. fixedCount++;
  352. }
  353. // 确保B1不是传感器(需要实际碰撞)
  354. if (b1Collider.sensor) {
  355. b1Collider.sensor = false;
  356. }
  357. }
  358. }
  359. // 检查Weapon子节点
  360. const weaponNode = this.findWeaponNode(block);
  361. if (weaponNode) {
  362. // 武器节点存在
  363. }
  364. }
  365. }
  366. // 随机位置小球
  367. positionBallRandomly() {
  368. if (!this.activeBall) return;
  369. const transform = this.activeBall.getComponent(UITransform);
  370. const ballRadius = transform ? transform.width / 2 : 25;
  371. // 计算可生成的范围(考虑小球半径,避免生成在边缘)
  372. const minX = this.gameBounds.left + ballRadius + 20; // 额外偏移,避免生成在边缘
  373. const maxX = this.gameBounds.right - ballRadius - 20;
  374. const minY = this.gameBounds.bottom + ballRadius + 20;
  375. const maxY = this.gameBounds.top - ballRadius - 20;
  376. // 获取GameArea节点
  377. const gameArea = find('Canvas/GameLevelUI/GameArea');
  378. if (!gameArea) {
  379. return;
  380. }
  381. // 查找PlacedBlocks节点,它包含所有放置的方块
  382. if (!this.placedBlocksContainer) {
  383. this.setRandomPositionDefault(minX, maxX, minY, maxY);
  384. return;
  385. }
  386. if (!this.placedBlocksContainer.isValid) {
  387. this.setRandomPositionDefault(minX, maxX, minY, maxY);
  388. return;
  389. }
  390. // 获取所有已放置的方块
  391. const placedBlocks = [];
  392. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  393. const block = this.placedBlocksContainer.children[i];
  394. // 检查是否是方块节点(通常以Block命名或有特定标识)
  395. if (block.name.includes('Block') || block.getChildByName('B1')) {
  396. placedBlocks.push(block);
  397. }
  398. }
  399. // 如果没有方块,使用默认随机位置
  400. if (placedBlocks.length === 0) {
  401. this.setRandomPositionDefault(minX, maxX, minY, maxY);
  402. return;
  403. }
  404. // 尝试找到一个不与任何方块重叠的位置
  405. let validPosition = false;
  406. let attempts = 0;
  407. const maxAttempts = 50; // 最大尝试次数
  408. let randomX, randomY;
  409. while (!validPosition && attempts < maxAttempts) {
  410. // 随机生成位置
  411. randomX = Math.random() * (maxX - minX) + minX;
  412. randomY = Math.random() * (maxY - minY) + minY;
  413. // 检查是否与任何方块重叠
  414. let overlapping = false;
  415. for (const block of placedBlocks) {
  416. // 获取方块的世界坐标
  417. const blockWorldPos = block.worldPosition;
  418. // 计算小球与方块的距离
  419. const distance = Math.sqrt(
  420. Math.pow(randomX - blockWorldPos.x, 2) +
  421. Math.pow(randomY - blockWorldPos.y, 2)
  422. );
  423. // 获取方块的尺寸
  424. const blockTransform = block.getComponent(UITransform);
  425. const blockSize = blockTransform ?
  426. Math.max(blockTransform.width, blockTransform.height) / 2 : 50;
  427. // 如果距离小于小球半径+方块尺寸的一半+安全距离,认为重叠
  428. const safeDistance = 20; // 额外安全距离
  429. if (distance < ballRadius + blockSize + safeDistance) {
  430. overlapping = true;
  431. break;
  432. }
  433. }
  434. // 如果没有重叠,找到了有效位置
  435. if (!overlapping) {
  436. validPosition = true;
  437. }
  438. attempts++;
  439. }
  440. // 如果找不到有效位置,使用默认位置(游戏区域底部中心)
  441. if (!validPosition) {
  442. randomX = (this.gameBounds.left + this.gameBounds.right) / 2;
  443. randomY = this.gameBounds.bottom + ballRadius + 50; // 底部上方50单位
  444. }
  445. // 将世界坐标转换为相对于GameArea的本地坐标
  446. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  447. this.activeBall.position = localPos;
  448. }
  449. // 设置默认随机位置
  450. setRandomPositionDefault(minX, maxX, minY, maxY) {
  451. // 随机生成位置
  452. const randomX = Math.random() * (maxX - minX) + minX;
  453. const randomY = Math.random() * (maxY - minY) + minY;
  454. // 将世界坐标转换为相对于GameArea的本地坐标
  455. const gameArea = find('Canvas/GameLevelUI/GameArea');
  456. if (gameArea) {
  457. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  458. this.activeBall.position = localPos;
  459. } else {
  460. // 直接设置位置(不太准确,但作为后备)
  461. this.activeBall.position = new Vec3(randomX - this.gameBounds.left, randomY - this.gameBounds.bottom, 0);
  462. }
  463. }
  464. // 设置碰撞组件
  465. setupCollider() {
  466. if (!this.activeBall) return;
  467. // 确保小球有刚体组件
  468. let rigidBody = this.activeBall.getComponent(RigidBody2D);
  469. if (!rigidBody) {
  470. rigidBody = this.activeBall.addComponent(RigidBody2D);
  471. rigidBody.type = 2; // Dynamic
  472. rigidBody.gravityScale = 0; // 不受重力影响
  473. rigidBody.enabledContactListener = true; // 启用碰撞监听
  474. rigidBody.fixedRotation = true; // 固定旋转
  475. rigidBody.allowSleep = false; // 不允许休眠
  476. rigidBody.linearDamping = 0; // 无线性阻尼,保持速度不衰减
  477. rigidBody.angularDamping = 0; // 无角阻尼
  478. } else {
  479. // 确保已有的刚体组件设置正确
  480. rigidBody.enabledContactListener = true;
  481. rigidBody.gravityScale = 0;
  482. rigidBody.linearDamping = 0; // 确保无线性阻尼,保持速度不衰减
  483. rigidBody.angularDamping = 0; // 确保无角阻尼
  484. rigidBody.allowSleep = false; // 不允许休眠
  485. }
  486. // 确保小球有碰撞组件
  487. let collider = this.activeBall.getComponent(CircleCollider2D);
  488. if (!collider) {
  489. collider = this.activeBall.addComponent(CircleCollider2D);
  490. collider.radius = this.radius || 25; // 使用已计算的半径或默认值
  491. collider.tag = 1; // 小球标签
  492. collider.group = 1; // 碰撞组1 - Ball组
  493. collider.sensor = false; // 非传感器(实际碰撞)
  494. collider.friction = 0; // 无摩擦
  495. collider.restitution = 1; // 完全弹性碰撞
  496. } else {
  497. // 确保已有的碰撞组件设置正确
  498. collider.sensor = false;
  499. collider.restitution = 1;
  500. collider.group = 1; // 确保是Ball组
  501. collider.tag = 1; // 确保标签正确
  502. }
  503. // === 使用全局回调监听器 ===
  504. const physics = PhysicsManager.getInstance()?.getSystem();
  505. if (physics) {
  506. // 先移除旧监听,避免重复注册
  507. physics.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  508. physics.off(Contact2DType.END_CONTACT, this.onEndContact, this);
  509. physics.off(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
  510. physics.off(Contact2DType.POST_SOLVE, this.onPostSolve, this);
  511. physics.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  512. physics.on(Contact2DType.END_CONTACT, this.onEndContact, this);
  513. physics.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
  514. physics.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
  515. }
  516. }
  517. // 碰撞回调 - 处理小球与方块以及小球之间的碰撞
  518. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  519. // 检查是否为小球之间的碰撞
  520. if (selfCollider.group === 1 && otherCollider.group === 1) {
  521. // 小球之间的碰撞 - 防止速度改变
  522. this.handleBallToBallCollision(selfCollider, otherCollider, contact);
  523. return;
  524. }
  525. // 判断哪个是小球,哪个是碰撞对象
  526. let ballNode: Node = null;
  527. let otherNode: Node = null;
  528. // 检查self是否为小球(组1)
  529. if (selfCollider.group === 1) {
  530. ballNode = selfCollider.node;
  531. otherNode = otherCollider.node;
  532. }
  533. // 检查other是否为小球(组1)
  534. else if (otherCollider.group === 1) {
  535. ballNode = otherCollider.node;
  536. otherNode = selfCollider.node;
  537. }
  538. // 如果没有找到小球,跳过处理
  539. if (!ballNode || !otherNode) {
  540. return;
  541. }
  542. // 检查是否为方块碰撞
  543. const nodeName = otherNode.name;
  544. const nodePath = this.getNodePath(otherNode);
  545. const hasWeaponChild = otherNode.getChildByName('Weapon') !== null;
  546. const isBlock =
  547. nodeName.includes('Block') ||
  548. nodePath.includes('Block') ||
  549. hasWeaponChild;
  550. // 如果是方块碰撞,检查防围困机制
  551. if (isBlock) {
  552. const ballId = ballNode.uuid;
  553. const currentTime = performance.now() / 1000; // 转换为秒
  554. // 检查是否处于穿透状态
  555. const phaseThroughEndTime = this.ballPhaseThrough.get(ballId);
  556. if (phaseThroughEndTime && currentTime < phaseThroughEndTime) {
  557. // 处于穿透状态,忽略碰撞但仍播放特效
  558. const ballAni = BallAni.getInstance();
  559. if (ballAni) {
  560. let contactPos: Vec3 = null;
  561. if (contact && (contact as any).getWorldManifold) {
  562. const wm = (contact as any).getWorldManifold();
  563. if (wm && wm.points && wm.points.length > 0) {
  564. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  565. }
  566. }
  567. if (!contactPos) {
  568. contactPos = otherNode.worldPosition.clone();
  569. }
  570. ballAni.playImpactEffect(contactPos);
  571. }
  572. // 禁用碰撞
  573. if (contact) {
  574. contact.disabled = true;
  575. }
  576. return;
  577. }
  578. // 记录撞击历史
  579. if (!this.ballHitHistory.has(ballId)) {
  580. this.ballHitHistory.set(ballId, []);
  581. }
  582. const hitHistory = this.ballHitHistory.get(ballId);
  583. hitHistory.push(currentTime);
  584. // 清理过期的撞击记录
  585. const timeThreshold = currentTime - this.antiTrapTimeWindow;
  586. while (hitHistory.length > 0 && hitHistory[0] < timeThreshold) {
  587. hitHistory.shift();
  588. }
  589. // 检查是否达到防围困条件
  590. if (hitHistory.length >= this.antiTrapHitThreshold) {
  591. // 获取当前偏移尝试次数
  592. const deflectionAttempts = this.ballDeflectionAttempts.get(ballId) || 0;
  593. if (deflectionAttempts < this.deflectionAttemptThreshold) {
  594. // 优先使用偏移方式
  595. this.ballDeflectionAttempts.set(ballId, deflectionAttempts + 1);
  596. // 应用增强偏移反弹
  597. const rigidBody = ballNode.getComponent(RigidBody2D);
  598. if (rigidBody && contact) {
  599. // 获取碰撞法线
  600. let normal = new Vec2(0, 1);
  601. if ((contact as any).getWorldManifold) {
  602. const wm = (contact as any).getWorldManifold();
  603. if (wm && wm.normal) {
  604. normal = new Vec2(wm.normal.x, wm.normal.y);
  605. }
  606. }
  607. // 计算增强偏移反弹方向
  608. const currentVelocity = rigidBody.linearVelocity;
  609. const currentDirection = new Vec2(currentVelocity.x, currentVelocity.y).normalize();
  610. const newDirection = this.calculateAntiTrapReflection(currentDirection, normal);
  611. // 应用新的速度方向
  612. const speed = currentVelocity.length();
  613. rigidBody.linearVelocity = new Vec2(newDirection.x * speed, newDirection.y * speed);
  614. console.log(`Ball ${ballId} applied anti-trap deflection (attempt ${deflectionAttempts + 1}/${this.deflectionAttemptThreshold})`);
  615. }
  616. // 清空撞击历史,给偏移一个机会
  617. hitHistory.length = 0;
  618. } else {
  619. // 偏移尝试次数已达上限,使用穿透
  620. this.ballPhaseThrough.set(ballId, currentTime + 0.5);
  621. // 重置偏移尝试次数
  622. this.ballDeflectionAttempts.set(ballId, 0);
  623. // 清空撞击历史
  624. hitHistory.length = 0;
  625. // 禁用当前碰撞
  626. if (contact) {
  627. contact.disabled = true;
  628. }
  629. console.log(`Ball ${ballId} entered phase-through mode after ${this.deflectionAttemptThreshold} deflection attempts failed`);
  630. return;
  631. }
  632. }
  633. }
  634. // 计算碰撞世界坐标
  635. let contactPos: Vec3 = null;
  636. if (contact && (contact as any).getWorldManifold) {
  637. const wm = (contact as any).getWorldManifold();
  638. if (wm && wm.points && wm.points.length > 0) {
  639. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  640. }
  641. }
  642. if (!contactPos) {
  643. contactPos = otherNode.worldPosition.clone();
  644. }
  645. // 播放撞击特效 - 对所有碰撞都播放特效
  646. const ballAni = BallAni.getInstance();
  647. if (ballAni) {
  648. ballAni.playImpactEffect(contactPos);
  649. }
  650. if (isBlock) {
  651. // 播放方块撞击动画
  652. if (ballAni) {
  653. ballAni.playBlockHitAnimation(otherNode);
  654. }
  655. // 通过事件检查是否可以发射子弹
  656. const eventBus = EventBus.getInstance();
  657. let canFire = true;
  658. // 发送检查事件,如果有监听器返回false则不发射
  659. eventBus.emit(GameEvents.BALL_FIRE_BULLET, { canFire: (value: boolean) => { canFire = value; } });
  660. if (canFire) {
  661. const now = performance.now();
  662. const lastTime = this.blockFireCooldown.get(otherNode.uuid) || 0;
  663. if (now - lastTime > this.FIRE_COOLDOWN * 1000) {
  664. this.blockFireCooldown.set(otherNode.uuid, now);
  665. this.fireBulletAt(otherNode, contactPos);
  666. }
  667. }
  668. }
  669. }
  670. /**
  671. * 处理小球之间的碰撞 - 保持恒定速度
  672. */
  673. private handleBallToBallCollision(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  674. const ball1 = selfCollider.node;
  675. const ball2 = otherCollider.node;
  676. const rigidBody1 = ball1.getComponent(RigidBody2D);
  677. const rigidBody2 = ball2.getComponent(RigidBody2D);
  678. if (!rigidBody1 || !rigidBody2) {
  679. return;
  680. }
  681. // 计算碰撞位置并播放撞击特效
  682. let contactPos: Vec3 = null;
  683. if (contact && (contact as any).getWorldManifold) {
  684. const wm = (contact as any).getWorldManifold();
  685. if (wm && wm.points && wm.points.length > 0) {
  686. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  687. }
  688. }
  689. if (!contactPos) {
  690. // 使用两个小球位置的中点作为碰撞位置
  691. const pos1 = ball1.worldPosition;
  692. const pos2 = ball2.worldPosition;
  693. contactPos = new Vec3(
  694. (pos1.x + pos2.x) / 2,
  695. (pos1.y + pos2.y) / 2,
  696. 0
  697. );
  698. }
  699. // 播放撞击特效
  700. const ballAni = BallAni.getInstance();
  701. if (ballAni) {
  702. ballAni.playImpactEffect(contactPos);
  703. }
  704. // 获取碰撞前的速度
  705. const velocity1 = rigidBody1.linearVelocity.clone();
  706. const velocity2 = rigidBody2.linearVelocity.clone();
  707. // 计算速度大小
  708. const speed1 = Math.sqrt(velocity1.x * velocity1.x + velocity1.y * velocity1.y);
  709. const speed2 = Math.sqrt(velocity2.x * velocity2.x + velocity2.y * velocity2.y);
  710. // 延迟一帧后恢复正确的速度,避免物理引擎的速度改变
  711. this.scheduleOnce(() => {
  712. if (ball1.isValid && rigidBody1.isValid) {
  713. const currentVel1 = rigidBody1.linearVelocity;
  714. const currentSpeed1 = Math.sqrt(currentVel1.x * currentVel1.x + currentVel1.y * currentVel1.y);
  715. // 如果速度发生了显著变化,恢复到目标速度
  716. if (Math.abs(currentSpeed1 - this.currentSpeed) > 5) {
  717. const normalizedVel1 = currentVel1.clone().normalize();
  718. rigidBody1.linearVelocity = new Vec2(
  719. normalizedVel1.x * this.currentSpeed,
  720. normalizedVel1.y * this.currentSpeed
  721. );
  722. }
  723. }
  724. if (ball2.isValid && rigidBody2.isValid) {
  725. const currentVel2 = rigidBody2.linearVelocity;
  726. const currentSpeed2 = Math.sqrt(currentVel2.x * currentVel2.x + currentVel2.y * currentVel2.y);
  727. // 如果速度发生了显著变化,恢复到目标速度
  728. if (Math.abs(currentSpeed2 - this.currentSpeed) > 5) {
  729. const normalizedVel2 = currentVel2.clone().normalize();
  730. rigidBody2.linearVelocity = new Vec2(
  731. normalizedVel2.x * this.currentSpeed,
  732. normalizedVel2.y * this.currentSpeed
  733. );
  734. }
  735. }
  736. }, 0.016); // 约一帧的时间
  737. }
  738. // 碰撞结束事件 - 简化版本
  739. onEndContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  740. // Debug log removed
  741. }
  742. // 碰撞预处理事件 - 简化版本
  743. onPreSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  744. // console.log('⚙️ 碰撞预处理:', otherCollider.node.name);
  745. }
  746. // 碰撞后处理事件 - 简化版本
  747. onPostSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  748. // console.log('✅ 碰撞后处理:', otherCollider.node.name);
  749. }
  750. // 计算反射向量
  751. calculateReflection(direction: Vec2, normal: Vec2): Vec2 {
  752. // 使用反射公式: R = V - 2(V·N)N
  753. const dot = direction.x * normal.x + direction.y * normal.y;
  754. const reflection = new Vec2(
  755. direction.x - 2 * dot * normal.x,
  756. direction.y - 2 * dot * normal.y
  757. );
  758. reflection.normalize();
  759. // 添加一些随机性,避免重复的反弹路径
  760. const randomAngle = (Math.random() - 0.5) * this.maxReflectionRandomness; // 随机角度
  761. const cos = Math.cos(randomAngle);
  762. const sin = Math.sin(randomAngle);
  763. // 应用随机旋转
  764. const randomizedReflection = new Vec2(
  765. reflection.x * cos - reflection.y * sin,
  766. reflection.x * sin + reflection.y * cos
  767. );
  768. // 确保反射方向不会太接近水平或垂直方向
  769. // 这有助于避免球在水平或垂直方向上来回反弹
  770. const minAngleFromAxis = 0.1; // 约5.7度
  771. // 检查是否接近水平方向
  772. if (Math.abs(randomizedReflection.y) < minAngleFromAxis) {
  773. // 调整y分量,使其远离水平方向
  774. const sign = randomizedReflection.y >= 0 ? 1 : -1;
  775. randomizedReflection.y = sign * (minAngleFromAxis + Math.random() * 0.1);
  776. // 重新归一化
  777. randomizedReflection.normalize();
  778. }
  779. // 检查是否接近垂直方向
  780. if (Math.abs(randomizedReflection.x) < minAngleFromAxis) {
  781. // 调整x分量,使其远离垂直方向
  782. const sign = randomizedReflection.x >= 0 ? 1 : -1;
  783. randomizedReflection.x = sign * (minAngleFromAxis + Math.random() * 0.1);
  784. // 重新归一化
  785. randomizedReflection.normalize();
  786. }
  787. randomizedReflection.normalize();
  788. // Debug log removed
  789. return randomizedReflection;
  790. }
  791. /**
  792. * 计算防围困增强偏移反弹方向
  793. * @param direction 当前方向
  794. * @param normal 碰撞法线
  795. * @returns 增强偏移后的反弹方向
  796. */
  797. calculateAntiTrapReflection(direction: Vec2, normal: Vec2): Vec2 {
  798. // 使用反射公式: R = V - 2(V·N)N
  799. const dot = direction.x * normal.x + direction.y * normal.y;
  800. const reflection = new Vec2(
  801. direction.x - 2 * dot * normal.x,
  802. direction.y - 2 * dot * normal.y
  803. );
  804. reflection.normalize();
  805. // 应用更强的随机偏移来帮助脱困
  806. const enhancedRandomness = this.maxReflectionRandomness * this.antiTrapDeflectionMultiplier;
  807. const randomAngle = (Math.random() - 0.5) * enhancedRandomness;
  808. const cos = Math.cos(randomAngle);
  809. const sin = Math.sin(randomAngle);
  810. // 应用随机旋转
  811. const randomizedReflection = new Vec2(
  812. reflection.x * cos - reflection.y * sin,
  813. reflection.x * sin + reflection.y * cos
  814. );
  815. // 更强的轴向偏移避免
  816. const minAngleFromAxis = 0.3; // 约17度,比普通反弹更大的偏移
  817. // 检查是否接近水平方向
  818. if (Math.abs(randomizedReflection.y) < minAngleFromAxis) {
  819. const sign = randomizedReflection.y >= 0 ? 1 : -1;
  820. randomizedReflection.y = sign * (minAngleFromAxis + Math.random() * 0.2);
  821. randomizedReflection.normalize();
  822. }
  823. // 检查是否接近垂直方向
  824. if (Math.abs(randomizedReflection.x) < minAngleFromAxis) {
  825. const sign = randomizedReflection.x >= 0 ? 1 : -1;
  826. randomizedReflection.x = sign * (minAngleFromAxis + Math.random() * 0.2);
  827. randomizedReflection.normalize();
  828. }
  829. randomizedReflection.normalize();
  830. console.log(`Applied anti-trap enhanced deflection with angle: ${randomAngle}`);
  831. return randomizedReflection;
  832. }
  833. /**
  834. * 从方块武器发射子弹攻击敌人 - 重构版本
  835. * 现在直接创建子弹实例并使用BulletController的实例方法
  836. * @param blockNode 激活的方块节点
  837. */
  838. fireBullet(blockNode: Node) {
  839. // Debug logs removed
  840. // 检查子弹预制体是否存在
  841. if (!this.bulletPrefab) {
  842. return;
  843. }
  844. // 查找方块中的Weapon节点
  845. const weaponNode = this.findWeaponNode(blockNode);
  846. if (!weaponNode) {
  847. const blockWorldPos = blockNode.worldPosition;
  848. const weaponConfig2: WeaponConfig | null = (blockNode as any)['weaponConfig'] || null;
  849. this.createAndFireBullet(blockWorldPos, weaponConfig2);
  850. return;
  851. }
  852. // 获取武器的世界坐标作为发射位置
  853. let firePosition: Vec3;
  854. try {
  855. firePosition = weaponNode.worldPosition;
  856. } catch (error) {
  857. // 备用方案:使用方块坐标
  858. firePosition = blockNode.worldPosition;
  859. }
  860. // 创建并发射子弹
  861. const weaponConfig: WeaponConfig | null = (blockNode as any)['weaponConfig'] || null;
  862. this.createAndFireBullet(firePosition, weaponConfig);
  863. }
  864. /**
  865. * 创建并发射子弹 - 使用新的WeaponBullet系统
  866. * @param firePosition 发射位置(世界坐标)
  867. * @param weaponConfig 武器配置
  868. */
  869. private createAndFireBullet(firePosition: Vec3, weaponConfig: WeaponConfig | null) {
  870. // 确保武器配置加载
  871. WeaponBullet.loadWeaponsData().then(() => {
  872. // 默认使用毛豆射手配置,后续可以根据方块类型动态选择
  873. const defaultWeaponId = 'pea_shooter';
  874. const finalConfig = weaponConfig || WeaponBullet.getWeaponConfig(defaultWeaponId);
  875. if (!finalConfig) {
  876. return;
  877. }
  878. // 创建子弹初始化数据
  879. const initData: BulletInitData = {
  880. weaponId: finalConfig.id,
  881. firePosition: firePosition,
  882. autoTarget: true,
  883. weaponConfig: finalConfig
  884. };
  885. // 验证初始化数据
  886. if (!WeaponBullet.validateInitData(initData)) {
  887. return;
  888. }
  889. // 判断是否为多发子弹(散射/连发等)
  890. const countCfg = finalConfig.bulletConfig.count;
  891. const isMultiShot = countCfg && countCfg.type !== 'single' && countCfg.amount > 1;
  892. // 查找GameArea(子弹统一添加到此节点)
  893. const gameArea = find('Canvas/GameLevelUI/GameArea');
  894. if (!gameArea) {
  895. return;
  896. }
  897. // === 根据武器配置选择合适的预制体 ===
  898. const needsTrail = !!(finalConfig.bulletConfig?.visual?.trailEffect);
  899. const prefabToUse: Prefab = (needsTrail && this.bulletContainerPrefab) ? this.bulletContainerPrefab : this.bulletPrefab;
  900. if (!prefabToUse) {
  901. return; // 如果没有可用的预制体则直接退出
  902. }
  903. if (isMultiShot) {
  904. // 使用批量创建逻辑
  905. const bullets = WeaponBullet.createBullets(initData, prefabToUse as any);
  906. bullets.forEach(b => {
  907. gameArea.addChild(b);
  908. });
  909. } else {
  910. // 单发逻辑(沿用原流程)
  911. const bullet = instantiate(prefabToUse);
  912. if (!bullet) {
  913. return;
  914. }
  915. gameArea.addChild(bullet);
  916. let weaponBullet = bullet.getComponent(WeaponBullet);
  917. if (!weaponBullet) {
  918. weaponBullet = bullet.addComponent(WeaponBullet);
  919. }
  920. weaponBullet.init(initData);
  921. }
  922. }).catch(error => {
  923. // 武器配置加载失败
  924. });
  925. }
  926. // 递归查找Weapon节点
  927. private findWeaponNode(node: Node): Node | null {
  928. // logs removed
  929. // 先检查当前节点是否有Weapon子节点
  930. const weaponNode = node.getChildByName('Weapon');
  931. if (weaponNode) {
  932. return weaponNode;
  933. }
  934. // 如果没有,递归检查所有子节点
  935. for (let i = 0; i < node.children.length; i++) {
  936. const child = node.children[i];
  937. const foundWeapon = this.findWeaponNode(child);
  938. if (foundWeapon) {
  939. return foundWeapon;
  940. }
  941. }
  942. // 如果都没找到,返回null
  943. return null;
  944. }
  945. // 获取节点的完整路径
  946. private getNodePath(node: Node): string {
  947. let path = node.name;
  948. let current = node;
  949. while (current.parent) {
  950. current = current.parent;
  951. path = current.name + '/' + path;
  952. }
  953. return path;
  954. }
  955. update(dt: number) {
  956. // 只有当小球已启动时才执行运动逻辑
  957. if (!this.ballStarted || !this.initialized) {
  958. return;
  959. }
  960. // 维持所有小球的恒定速度
  961. this.maintainAllBallsSpeed();
  962. // 清理过期的防围困状态
  963. this.cleanupExpiredAntiTrapStates();
  964. // 定期检查小球是否接近方块但没有触发碰撞(调试用)
  965. if (this.activeBall && this.activeBall.isValid) {
  966. this.debugCheckNearBlocks();
  967. }
  968. }
  969. /**
  970. * 维持所有小球的恒定速度
  971. */
  972. private maintainAllBallsSpeed() {
  973. // 维持主小球速度
  974. if (this.activeBall && this.activeBall.isValid) {
  975. this.maintainBallSpeed(this.activeBall);
  976. }
  977. // 维持额外小球的速度
  978. const gameArea = find('Canvas/GameLevelUI/GameArea');
  979. if (gameArea) {
  980. const additionalBalls = gameArea.children.filter(child =>
  981. child.name === 'AdditionalBall' && child.isValid
  982. );
  983. for (const ball of additionalBalls) {
  984. this.maintainBallSpeed(ball);
  985. }
  986. }
  987. }
  988. /**
  989. * 维持单个小球的恒定速度
  990. */
  991. private maintainBallSpeed(ball: Node) {
  992. const rigidBody = ball.getComponent(RigidBody2D);
  993. if (!rigidBody) return;
  994. // 获取当前速度
  995. const currentVelocity = rigidBody.linearVelocity;
  996. const speed = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
  997. // 如果速度过低或过高,重新设置速度以维持恒定运动
  998. if (speed < this.currentSpeed * 0.85 || speed > this.currentSpeed * 1.15) {
  999. // 保持当前方向,但调整速度大小
  1000. if (speed > 0.1) {
  1001. const normalizedVelocity = currentVelocity.clone().normalize();
  1002. rigidBody.linearVelocity = new Vec2(
  1003. normalizedVelocity.x * this.currentSpeed,
  1004. normalizedVelocity.y * this.currentSpeed
  1005. );
  1006. } else {
  1007. // 如果速度几乎为0,给一个随机方向
  1008. const angle = Math.random() * Math.PI * 2;
  1009. rigidBody.linearVelocity = new Vec2(
  1010. Math.cos(angle) * this.currentSpeed,
  1011. Math.sin(angle) * this.currentSpeed
  1012. );
  1013. }
  1014. }
  1015. // 更新主小球的方向向量(用于其他逻辑)
  1016. if (ball === this.activeBall && speed > 1.0) {
  1017. this.direction.x = currentVelocity.x / speed;
  1018. this.direction.y = currentVelocity.y / speed;
  1019. }
  1020. }
  1021. // 调试方法:检查小球是否接近方块但没有触发物理碰撞
  1022. private debugCheckCounter = 0;
  1023. private debugCheckNearBlocks() {
  1024. this.debugCheckCounter++;
  1025. // 每60帧(约1秒)检查一次
  1026. if (this.debugCheckCounter % 60 !== 0) return;
  1027. const ballPos = this.activeBall.worldPosition;
  1028. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) return;
  1029. let nearestDistance = Infinity;
  1030. let nearestBlock = null;
  1031. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  1032. const block = this.placedBlocksContainer.children[i];
  1033. if (block.name.includes('Block') || block.getChildByName('B1')) {
  1034. const blockPos = block.worldPosition;
  1035. const distance = Math.sqrt(
  1036. Math.pow(ballPos.x - blockPos.x, 2) +
  1037. Math.pow(ballPos.y - blockPos.y, 2)
  1038. );
  1039. if (distance < nearestDistance) {
  1040. nearestDistance = distance;
  1041. nearestBlock = block;
  1042. }
  1043. }
  1044. }
  1045. if (nearestBlock && nearestDistance < 100) {
  1046. // 检查小球的碰撞体状态
  1047. const ballCollider = this.activeBall.getComponent(Collider2D);
  1048. if (ballCollider) {
  1049. if (ballCollider instanceof CircleCollider2D) {
  1050. // 小球碰撞半径检查
  1051. }
  1052. }
  1053. // 检查小球的刚体状态
  1054. const ballRigidBody = this.activeBall.getComponent(RigidBody2D);
  1055. if (ballRigidBody) {
  1056. // 刚体状态检查
  1057. }
  1058. // 检查最近的方块碰撞体
  1059. const blockCollider = nearestBlock.getComponent(Collider2D);
  1060. if (blockCollider) {
  1061. // 方块碰撞体检查
  1062. }
  1063. }
  1064. }
  1065. // 初始化方向
  1066. initializeDirection() {
  1067. // 随机初始方向
  1068. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  1069. this.direction.x = Math.cos(angle);
  1070. this.direction.y = Math.sin(angle);
  1071. this.direction.normalize();
  1072. // 设置初始速度
  1073. if (this.activeBall) {
  1074. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  1075. if (rigidBody) {
  1076. rigidBody.linearVelocity = new Vec2(
  1077. this.direction.x * this.currentSpeed,
  1078. this.direction.y * this.currentSpeed
  1079. );
  1080. }
  1081. }
  1082. }
  1083. // 初始化球的参数 - 公开方法,供GameManager调用
  1084. public initialize() {
  1085. this.calculateGameBounds();
  1086. this.createBall();
  1087. // 检查方块碰撞体(延迟执行,确保方块已放置)
  1088. this.scheduleOnce(() => {
  1089. this.checkBlockColliders();
  1090. }, 0.5);
  1091. }
  1092. // 启动小球 - 公开方法,在确定按钮点击后调用
  1093. public startBall() {
  1094. // 检查ballPrefab是否设置
  1095. if (!this.ballPrefab) {
  1096. console.error('[BallController] ballPrefab 未设置,无法创建小球');
  1097. return;
  1098. }
  1099. // 如果还没有初始化,先初始化
  1100. if (!this.initialized) {
  1101. this.initialize();
  1102. }
  1103. // 确保小球存在且有效
  1104. if (!this.activeBall || !this.activeBall.isValid) {
  1105. this.createBall();
  1106. }
  1107. // 检查小球是否成功创建
  1108. if (!this.activeBall) {
  1109. console.error('[BallController] 小球创建失败');
  1110. return;
  1111. }
  1112. // 重新定位小球,避免与方块重叠
  1113. this.positionBallRandomly();
  1114. // 确保物理组件设置正确
  1115. this.setupCollider();
  1116. // 初始化运动方向并开始运动
  1117. this.initializeDirection();
  1118. // 设置运动状态
  1119. this.ballStarted = true;
  1120. console.log('[BallController] 小球启动完成');
  1121. }
  1122. /**
  1123. * 暂停小球运动:记录当前速度并停止刚体
  1124. */
  1125. public pauseBall() {
  1126. if (this.isPaused) return;
  1127. this.isPaused = true;
  1128. this.ballStarted = false;
  1129. if (this.activeBall && this.activeBall.isValid) {
  1130. const rb = this.activeBall.getComponent(RigidBody2D);
  1131. if (rb) {
  1132. this.pausedVelocity = rb.linearVelocity.clone();
  1133. rb.linearVelocity = new Vec2(0, 0);
  1134. rb.sleep();
  1135. }
  1136. }
  1137. }
  1138. /**
  1139. * 恢复小球运动:恢复暂停前的速度
  1140. */
  1141. public resumeBall() {
  1142. if (!this.isPaused) return;
  1143. this.isPaused = false;
  1144. this.ballStarted = true;
  1145. console.log('恢复小球运动');
  1146. if (this.activeBall && this.activeBall.isValid) {
  1147. const rb = this.activeBall.getComponent(RigidBody2D);
  1148. if (rb) {
  1149. rb.wakeUp();
  1150. const hasPrevVelocity = this.pausedVelocity && (this.pausedVelocity.x !== 0 || this.pausedVelocity.y !== 0);
  1151. if (hasPrevVelocity) {
  1152. rb.linearVelocity = this.pausedVelocity.clone();
  1153. } else {
  1154. // 若没有记录速度,则重新初始化方向
  1155. this.initializeDirection();
  1156. }
  1157. }
  1158. }
  1159. }
  1160. /**
  1161. * 从给定世界坐标发射子弹
  1162. */
  1163. private fireBulletAt(blockNode: Node, fireWorldPos: Vec3) {
  1164. // 检查子弹预制体是否存在
  1165. if (!this.bulletPrefab) {
  1166. return;
  1167. }
  1168. // 直接使用碰撞世界坐标作为发射点
  1169. const weaponConfig: WeaponConfig | null = (blockNode as any)['weaponConfig'] || null;
  1170. this.createAndFireBullet(fireWorldPos, weaponConfig);
  1171. }
  1172. /**
  1173. * 重置球控制器状态 - 游戏重置时调用
  1174. */
  1175. public resetBallController() {
  1176. console.log('[BallController] 重置球控制器状态');
  1177. // 停止球的运动
  1178. this.ballStarted = false;
  1179. this.isPaused = false;
  1180. // 清理暂停状态
  1181. this.pausedVelocity = new Vec2();
  1182. // 销毁当前活动的球
  1183. if (this.activeBall && this.activeBall.isValid) {
  1184. console.log('[BallController] 销毁当前活动的球');
  1185. this.activeBall.destroy();
  1186. }
  1187. this.activeBall = null;
  1188. // 重置初始化状态
  1189. this.initialized = false;
  1190. // 清理冷却时间
  1191. this.blockFireCooldown.clear();
  1192. // 清理防围困状态数据
  1193. this.ballHitHistory.clear();
  1194. this.ballPhaseThrough.clear();
  1195. this.ballDeflectionAttempts.clear();
  1196. // 重置球速
  1197. this.updateBallSpeed();
  1198. console.log('[BallController] 球控制器重置完成');
  1199. }
  1200. /**
  1201. * 清理过期的防围困状态
  1202. */
  1203. private cleanupExpiredAntiTrapStates() {
  1204. const currentTime = performance.now() / 1000;
  1205. // 清理过期的穿透状态
  1206. for (const [ballId, endTime] of this.ballPhaseThrough.entries()) {
  1207. if (currentTime >= endTime) {
  1208. this.ballPhaseThrough.delete(ballId);
  1209. }
  1210. }
  1211. // 检查并重置长时间未频繁撞击的球的偏移尝试次数
  1212. for (const [ballId, hitHistory] of this.ballHitHistory.entries()) {
  1213. // 如果撞击历史为空或最近一次撞击超过时间窗口的一半,重置偏移尝试次数
  1214. if (hitHistory.length === 0 ||
  1215. (hitHistory.length > 0 && currentTime - hitHistory[hitHistory.length - 1] > this.antiTrapTimeWindow / 2)) {
  1216. if (this.ballDeflectionAttempts.has(ballId)) {
  1217. this.ballDeflectionAttempts.set(ballId, 0);
  1218. }
  1219. }
  1220. }
  1221. }
  1222. /**
  1223. * 清理单个小球的防围困状态数据
  1224. * @param ballId 小球的唯一标识符
  1225. */
  1226. public cleanupBallAntiTrapState(ballId: string) {
  1227. this.ballHitHistory.delete(ballId);
  1228. this.ballPhaseThrough.delete(ballId);
  1229. this.ballDeflectionAttempts.delete(ballId);
  1230. console.log(`Cleaned up anti-trap state for ball ${ballId}`);
  1231. }
  1232. onDestroy() {
  1233. // 清理事件监听
  1234. const eventBus = EventBus.getInstance();
  1235. eventBus.off(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
  1236. eventBus.off(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  1237. eventBus.off(GameEvents.RESET_BALL_CONTROLLER, this.onResetBallControllerEvent, this);
  1238. // 清理防围困状态数据
  1239. this.ballHitHistory.clear();
  1240. this.ballPhaseThrough.clear();
  1241. }
  1242. private updateBallSpeed() {
  1243. const skillManager = PersistentSkillManager.getInstance();
  1244. if (skillManager) {
  1245. this.currentSpeed = skillManager.applyBallSpeedBonus(this.baseSpeed);
  1246. } else {
  1247. this.currentSpeed = this.baseSpeed;
  1248. }
  1249. }
  1250. }