BallController.ts 65 KB

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