BallController.ts 67 KB

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