BallController.ts 61 KB

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