BallController.ts 58 KB

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