BallController.ts 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664
  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. // 根据新的预制体结构,检查B1/Weapon路径
  636. const b1Node = otherNode.getChildByName('B1');
  637. const hasWeaponChild = b1Node ? b1Node.getChildByName('Weapon') !== null : otherNode.getChildByName('Weapon') !== null;
  638. const isBlock =
  639. nodeName.includes('Block') ||
  640. nodePath.includes('Block') ||
  641. hasWeaponChild;
  642. // 如果是方块碰撞,检查防围困机制
  643. if (isBlock) {
  644. const ballId = ballNode.uuid;
  645. const currentTime = performance.now() / 1000; // 转换为秒
  646. // 检查是否处于穿透状态
  647. const phaseThroughEndTime = this.ballPhaseThrough.get(ballId);
  648. if (phaseThroughEndTime && currentTime < phaseThroughEndTime) {
  649. // 处于穿透状态,忽略碰撞但仍播放特效
  650. const ballAni = BallAni.getInstance();
  651. if (ballAni) {
  652. let contactPos: Vec3 = null;
  653. if (contact && (contact as any).getWorldManifold) {
  654. const wm = (contact as any).getWorldManifold();
  655. if (wm && wm.points && wm.points.length > 0) {
  656. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  657. }
  658. }
  659. if (!contactPos) {
  660. contactPos = otherNode.worldPosition.clone();
  661. }
  662. ballAni.playImpactEffect(contactPos);
  663. }
  664. // 禁用碰撞
  665. if (contact) {
  666. contact.disabled = true;
  667. }
  668. return;
  669. }
  670. // 记录撞击历史
  671. if (!this.ballHitHistory.has(ballId)) {
  672. this.ballHitHistory.set(ballId, []);
  673. }
  674. const hitHistory = this.ballHitHistory.get(ballId);
  675. hitHistory.push(currentTime);
  676. // 清理过期的撞击记录
  677. const timeThreshold = currentTime - this.antiTrapTimeWindow;
  678. while (hitHistory.length > 0 && hitHistory[0] < timeThreshold) {
  679. hitHistory.shift();
  680. }
  681. // 检查是否达到防围困条件
  682. if (hitHistory.length >= this.antiTrapHitThreshold) {
  683. // 获取当前偏移尝试次数
  684. const deflectionAttempts = this.ballDeflectionAttempts.get(ballId) || 0;
  685. if (deflectionAttempts < this.deflectionAttemptThreshold) {
  686. // 优先使用偏移方式
  687. this.ballDeflectionAttempts.set(ballId, deflectionAttempts + 1);
  688. // 应用增强偏移反弹
  689. const rigidBody = ballNode.getComponent(RigidBody2D);
  690. if (rigidBody && contact) {
  691. // 获取碰撞法线
  692. let normal = new Vec2(0, 1);
  693. if ((contact as any).getWorldManifold) {
  694. const wm = (contact as any).getWorldManifold();
  695. if (wm && wm.normal) {
  696. normal = new Vec2(wm.normal.x, wm.normal.y);
  697. }
  698. }
  699. // 计算增强偏移反弹方向
  700. const currentVelocity = rigidBody.linearVelocity;
  701. const currentDirection = new Vec2(currentVelocity.x, currentVelocity.y).normalize();
  702. const newDirection = this.calculateAntiTrapReflection(currentDirection, normal);
  703. // 应用新的速度方向
  704. const speed = currentVelocity.length();
  705. rigidBody.linearVelocity = new Vec2(newDirection.x * speed, newDirection.y * speed);
  706. }
  707. // 清空撞击历史,给偏移一个机会
  708. hitHistory.length = 0;
  709. } else {
  710. // 偏移尝试次数已达上限,使用穿透
  711. this.ballPhaseThrough.set(ballId, currentTime + 0.5);
  712. // 重置偏移尝试次数
  713. this.ballDeflectionAttempts.set(ballId, 0);
  714. // 清空撞击历史
  715. hitHistory.length = 0;
  716. // 禁用当前碰撞
  717. if (contact) {
  718. contact.disabled = true;
  719. }
  720. return;
  721. }
  722. }
  723. }
  724. // 计算碰撞世界坐标
  725. let contactPos: Vec3 = null;
  726. if (contact && (contact as any).getWorldManifold) {
  727. const wm = (contact as any).getWorldManifold();
  728. if (wm && wm.points && wm.points.length > 0) {
  729. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  730. }
  731. }
  732. if (!contactPos) {
  733. contactPos = otherNode.worldPosition.clone();
  734. }
  735. // 播放撞击特效 - 对所有碰撞都播放特效
  736. const ballAni = BallAni.getInstance();
  737. if (ballAni) {
  738. ballAni.playImpactEffect(contactPos);
  739. }
  740. if (isBlock) {
  741. // 播放方块撞击动画
  742. if (ballAni) {
  743. ballAni.playBlockHitAnimation(otherNode);
  744. }
  745. // 通过事件检查是否可以发射子弹
  746. const eventBus = EventBus.getInstance();
  747. let canFire = true;
  748. // 发送检查事件,如果有监听器返回false则不发射
  749. eventBus.emit(GameEvents.BALL_FIRE_BULLET, { canFire: (value: boolean) => { canFire = value; } });
  750. if (canFire) {
  751. const now = performance.now();
  752. const lastTime = this.blockFireCooldown.get(otherNode.uuid) || 0;
  753. if (now - lastTime > this.FIRE_COOLDOWN * 1000) {
  754. this.blockFireCooldown.set(otherNode.uuid, now);
  755. this.fireBulletAt(otherNode, contactPos);
  756. }
  757. }
  758. }
  759. }
  760. /**
  761. * 处理小球之间的碰撞 - 保持恒定速度
  762. */
  763. private handleBallToBallCollision(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  764. const ball1 = selfCollider.node;
  765. const ball2 = otherCollider.node;
  766. const rigidBody1 = ball1.getComponent(RigidBody2D);
  767. const rigidBody2 = ball2.getComponent(RigidBody2D);
  768. if (!rigidBody1 || !rigidBody2) {
  769. return;
  770. }
  771. // 计算碰撞位置并播放撞击特效
  772. let contactPos: Vec3 = null;
  773. if (contact && (contact as any).getWorldManifold) {
  774. const wm = (contact as any).getWorldManifold();
  775. if (wm && wm.points && wm.points.length > 0) {
  776. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  777. }
  778. }
  779. if (!contactPos) {
  780. // 使用两个小球位置的中点作为碰撞位置
  781. const pos1 = ball1.worldPosition;
  782. const pos2 = ball2.worldPosition;
  783. contactPos = new Vec3(
  784. (pos1.x + pos2.x) / 2,
  785. (pos1.y + pos2.y) / 2,
  786. 0
  787. );
  788. }
  789. // 播放撞击特效
  790. const ballAni = BallAni.getInstance();
  791. if (ballAni) {
  792. ballAni.playImpactEffect(contactPos);
  793. }
  794. // 获取碰撞前的速度
  795. const velocity1 = rigidBody1.linearVelocity.clone();
  796. const velocity2 = rigidBody2.linearVelocity.clone();
  797. // 计算速度大小
  798. const speed1 = Math.sqrt(velocity1.x * velocity1.x + velocity1.y * velocity1.y);
  799. const speed2 = Math.sqrt(velocity2.x * velocity2.x + velocity2.y * velocity2.y);
  800. // 延迟一帧后恢复正确的速度,避免物理引擎的速度改变
  801. this.scheduleOnce(() => {
  802. if (ball1.isValid && rigidBody1.isValid) {
  803. const currentVel1 = rigidBody1.linearVelocity;
  804. const currentSpeed1 = Math.sqrt(currentVel1.x * currentVel1.x + currentVel1.y * currentVel1.y);
  805. // 如果速度发生了显著变化,恢复到目标速度
  806. if (Math.abs(currentSpeed1 - this.currentSpeed) > 5) {
  807. const normalizedVel1 = currentVel1.clone().normalize();
  808. rigidBody1.linearVelocity = new Vec2(
  809. normalizedVel1.x * this.currentSpeed,
  810. normalizedVel1.y * this.currentSpeed
  811. );
  812. }
  813. }
  814. if (ball2.isValid && rigidBody2.isValid) {
  815. const currentVel2 = rigidBody2.linearVelocity;
  816. const currentSpeed2 = Math.sqrt(currentVel2.x * currentVel2.x + currentVel2.y * currentVel2.y);
  817. // 如果速度发生了显著变化,恢复到目标速度
  818. if (Math.abs(currentSpeed2 - this.currentSpeed) > 5) {
  819. const normalizedVel2 = currentVel2.clone().normalize();
  820. rigidBody2.linearVelocity = new Vec2(
  821. normalizedVel2.x * this.currentSpeed,
  822. normalizedVel2.y * this.currentSpeed
  823. );
  824. }
  825. }
  826. }, 0.016); // 约一帧的时间
  827. }
  828. // 这些方法已被移除,因为它们没有实际功能且会造成性能开销
  829. // 如果需要这些碰撞事件,请在具体需要时重新实现
  830. // 计算反射向量
  831. calculateReflection(direction: Vec2, normal: Vec2): Vec2 {
  832. // 使用反射公式: R = V - 2(V·N)N
  833. const dot = direction.x * normal.x + direction.y * normal.y;
  834. const reflection = new Vec2(
  835. direction.x - 2 * dot * normal.x,
  836. direction.y - 2 * dot * normal.y
  837. );
  838. reflection.normalize();
  839. // 添加一些随机性,避免重复的反弹路径
  840. const randomAngle = (Math.random() - 0.5) * this.maxReflectionRandomness; // 随机角度
  841. const cos = Math.cos(randomAngle);
  842. const sin = Math.sin(randomAngle);
  843. // 应用随机旋转
  844. const randomizedReflection = new Vec2(
  845. reflection.x * cos - reflection.y * sin,
  846. reflection.x * sin + reflection.y * cos
  847. );
  848. // 确保反射方向不会太接近水平或垂直方向
  849. // 这有助于避免球在水平或垂直方向上来回反弹
  850. const minAngleFromAxis = 0.1; // 约5.7度
  851. // 检查是否接近水平方向
  852. if (Math.abs(randomizedReflection.y) < minAngleFromAxis) {
  853. // 调整y分量,使其远离水平方向
  854. const sign = randomizedReflection.y >= 0 ? 1 : -1;
  855. randomizedReflection.y = sign * (minAngleFromAxis + Math.random() * 0.1);
  856. // 重新归一化
  857. randomizedReflection.normalize();
  858. }
  859. // 检查是否接近垂直方向
  860. if (Math.abs(randomizedReflection.x) < minAngleFromAxis) {
  861. // 调整x分量,使其远离垂直方向
  862. const sign = randomizedReflection.x >= 0 ? 1 : -1;
  863. randomizedReflection.x = sign * (minAngleFromAxis + Math.random() * 0.1);
  864. // 重新归一化
  865. randomizedReflection.normalize();
  866. }
  867. randomizedReflection.normalize();
  868. // Debug log removed
  869. return randomizedReflection;
  870. }
  871. /**
  872. * 计算防围困增强偏移反弹方向
  873. * @param direction 当前方向
  874. * @param normal 碰撞法线
  875. * @returns 增强偏移后的反弹方向
  876. */
  877. calculateAntiTrapReflection(direction: Vec2, normal: Vec2): Vec2 {
  878. // 使用反射公式: R = V - 2(V·N)N
  879. const dot = direction.x * normal.x + direction.y * normal.y;
  880. const reflection = new Vec2(
  881. direction.x - 2 * dot * normal.x,
  882. direction.y - 2 * dot * normal.y
  883. );
  884. reflection.normalize();
  885. // 应用更强的随机偏移来帮助脱困
  886. const enhancedRandomness = this.maxReflectionRandomness * this.antiTrapDeflectionMultiplier;
  887. const randomAngle = (Math.random() - 0.5) * enhancedRandomness;
  888. const cos = Math.cos(randomAngle);
  889. const sin = Math.sin(randomAngle);
  890. // 应用随机旋转
  891. const randomizedReflection = new Vec2(
  892. reflection.x * cos - reflection.y * sin,
  893. reflection.x * sin + reflection.y * cos
  894. );
  895. // 更强的轴向偏移避免
  896. const minAngleFromAxis = 0.3; // 约17度,比普通反弹更大的偏移
  897. // 检查是否接近水平方向
  898. if (Math.abs(randomizedReflection.y) < minAngleFromAxis) {
  899. const sign = randomizedReflection.y >= 0 ? 1 : -1;
  900. randomizedReflection.y = sign * (minAngleFromAxis + Math.random() * 0.2);
  901. randomizedReflection.normalize();
  902. }
  903. // 检查是否接近垂直方向
  904. if (Math.abs(randomizedReflection.x) < minAngleFromAxis) {
  905. const sign = randomizedReflection.x >= 0 ? 1 : -1;
  906. randomizedReflection.x = sign * (minAngleFromAxis + Math.random() * 0.2);
  907. randomizedReflection.normalize();
  908. }
  909. randomizedReflection.normalize();
  910. console.log(`Applied anti-trap enhanced deflection with angle: ${randomAngle}`);
  911. return randomizedReflection;
  912. }
  913. /**
  914. * 从方块武器发射子弹攻击敌人 - 重构版本
  915. * 现在直接创建子弹实例并使用BulletController的实例方法
  916. * @param blockNode 激活的方块节点
  917. */
  918. fireBullet(blockNode: Node) {
  919. // Debug logs removed
  920. // 检查子弹预制体是否存在
  921. if (!this.bulletPrefab) {
  922. return;
  923. }
  924. // 查找方块中的Weapon节点
  925. const weaponNode = this.findWeaponNode(blockNode);
  926. let firePosition: Vec3;
  927. if (!weaponNode) {
  928. firePosition = blockNode.worldPosition;
  929. } else {
  930. // 获取武器的世界坐标作为发射位置
  931. try {
  932. firePosition = weaponNode.worldPosition;
  933. } catch (error) {
  934. // 备用方案:使用方块坐标
  935. firePosition = blockNode.worldPosition;
  936. }
  937. }
  938. // 通过事件系统发射子弹,这样可以被暂停检查拦截
  939. EventBus.getInstance().emit(GameEvents.BALL_FIRE_BULLET, blockNode, firePosition);
  940. }
  941. /**
  942. * 创建并发射子弹 - 使用新的WeaponBullet系统
  943. * @param firePosition 发射位置(世界坐标)
  944. * @param weaponNode 武器节点(包含WeaponInfo组件)
  945. */
  946. private createAndFireBullet(firePosition: Vec3, weaponNode: Node | null) {
  947. // 确保武器配置加载
  948. WeaponBullet.loadWeaponsData().then(() => {
  949. let finalConfig: WeaponConfig | null = null;
  950. // 优先从武器节点的WeaponInfo组件获取配置
  951. if (weaponNode && weaponNode.isValid) {
  952. const weaponInfo = weaponNode.getComponent(WeaponInfo);
  953. if (weaponInfo) {
  954. finalConfig = weaponInfo.getWeaponConfig();
  955. console.log(`[BallController] 从武器节点获取武器配置: ${finalConfig?.name || '未知'}`);
  956. // 检查武器是否可以开火
  957. if (!weaponInfo.canFire()) {
  958. console.log(`[BallController] 武器 ${finalConfig?.name || '未知'} 冷却中,无法开火`);
  959. return;
  960. }
  961. // 记录开火时间
  962. weaponInfo.recordFireTime();
  963. }
  964. }
  965. // 如果没有从武器节点获取到配置,使用默认配置
  966. if (!finalConfig) {
  967. const defaultWeaponId = 'pea_shooter';
  968. finalConfig = WeaponBullet.getWeaponConfig(defaultWeaponId);
  969. console.log(`[BallController] 使用默认武器配置: ${defaultWeaponId}`);
  970. }
  971. if (!finalConfig) {
  972. console.warn(`[BallController] 无法获取武器配置,取消发射`);
  973. return;
  974. }
  975. // 获取WeaponInfo组件(如果有的话)
  976. let weaponInfoComponent: WeaponInfo | null = null;
  977. if (weaponNode && weaponNode.isValid) {
  978. weaponInfoComponent = weaponNode.getComponent(WeaponInfo);
  979. }
  980. // 创建子弹初始化数据
  981. const initData: BulletInitData = {
  982. weaponId: finalConfig.id,
  983. firePosition: firePosition,
  984. autoTarget: true,
  985. weaponConfig: finalConfig,
  986. weaponInfo: weaponInfoComponent
  987. };
  988. // 验证初始化数据
  989. if (!WeaponBullet.validateInitData(initData)) {
  990. console.warn(`[BallController] 子弹初始化数据验证失败`);
  991. return;
  992. }
  993. // 查找GameArea(子弹统一添加到此节点)
  994. const gameArea = find('Canvas/GameLevelUI/GameArea');
  995. if (!gameArea) {
  996. console.warn(`[BallController] 未找到GameArea节点,无法发射子弹`);
  997. return;
  998. }
  999. // === 根据武器配置选择合适的预制体 ===
  1000. const trailEffect = finalConfig.bulletConfig?.visual?.trailEffect;
  1001. // 尖胡萝卜特殊处理:使用PelletContainer预制体但激活Spine节点
  1002. const isSharpCarrot = finalConfig.id === 'sharp_carrot';
  1003. // 当trailEffect为true或者是尖胡萝卜时都使用容器预制体
  1004. const needsContainerPrefab = Boolean(trailEffect) || isSharpCarrot;
  1005. const prefabToUse: Prefab = (needsContainerPrefab && this.bulletContainerPrefab) ? this.bulletContainerPrefab : this.bulletPrefab;
  1006. if (!prefabToUse) {
  1007. console.warn(`[BallController] 没有可用的子弹预制体`);
  1008. return;
  1009. }
  1010. // 使用批量创建逻辑
  1011. console.log(`[BallController] 开始创建子弹 - 武器: ${finalConfig.name}, 预制体: ${prefabToUse ? prefabToUse.name : 'null'}`);
  1012. const bullets = WeaponBullet.createBullets(initData, prefabToUse as any);
  1013. console.log(`[BallController] WeaponBullet.createBullets 返回了 ${bullets.length} 个子弹`);
  1014. bullets.forEach((b, index) => {
  1015. console.log(`[BallController] 添加第 ${index + 1} 个子弹到场景 - 子弹节点: ${b ? b.name : 'null'}, 是否有效: ${b ? b.isValid : 'false'}`);
  1016. if (b && b.isValid) {
  1017. gameArea.addChild(b);
  1018. console.log(`[BallController] 子弹 ${index + 1} 成功添加到场景,世界坐标: ${b.worldPosition}`);
  1019. } else {
  1020. console.error(`[BallController] 子弹 ${index + 1} 无效,无法添加到场景`);
  1021. }
  1022. });
  1023. console.log(`[BallController] 成功发射 ${bullets.length} 发子弹,武器: ${finalConfig.name}`);
  1024. }).catch(error => {
  1025. console.error(`[BallController] 武器配置加载失败:`, error);
  1026. });
  1027. }
  1028. // 递归查找Weapon节点
  1029. private findWeaponNode(node: Node): Node | null {
  1030. // 检查节点是否有效
  1031. if (!node || !node.isValid) {
  1032. console.warn('[BallController] findWeaponNode: 传入的节点无效');
  1033. return null;
  1034. }
  1035. // 根据新的预制体结构,武器节点直接位于方块根节点下
  1036. const weaponNode = node.getChildByName('Weapon');
  1037. if (weaponNode) {
  1038. return weaponNode;
  1039. }
  1040. // 兼容旧结构:如果直接查找失败,尝试B1/Weapon路径
  1041. const b1Node = node.getChildByName('B1');
  1042. if (b1Node) {
  1043. const b1WeaponNode = b1Node.getChildByName('Weapon');
  1044. if (b1WeaponNode) {
  1045. return b1WeaponNode;
  1046. }
  1047. }
  1048. // 最后使用递归方式查找(兼容其他可能的结构)
  1049. for (let i = 0; i < node.children.length; i++) {
  1050. const child = node.children[i];
  1051. const foundWeapon = this.findWeaponNode(child);
  1052. if (foundWeapon) {
  1053. return foundWeapon;
  1054. }
  1055. }
  1056. // 如果都没找到,返回null
  1057. console.warn('[BallController] 方块', node.name, '中未找到武器节点');
  1058. return null;
  1059. }
  1060. // 获取节点的完整路径
  1061. private getNodePath(node: Node): string {
  1062. let path = node.name;
  1063. let current = node;
  1064. while (current.parent) {
  1065. current = current.parent;
  1066. path = current.name + '/' + path;
  1067. }
  1068. return path;
  1069. }
  1070. update(dt: number) {
  1071. // 只有当小球已启动时才执行运动逻辑
  1072. if (!this.ballStarted || !this.initialized) {
  1073. return;
  1074. }
  1075. // 维持所有小球的恒定速度
  1076. this.maintainAllBallsSpeed();
  1077. // 清理过期的防围困状态
  1078. this.cleanupExpiredAntiTrapStates();
  1079. // 定期检查小球是否接近方块但没有触发碰撞(调试用)
  1080. if (this.activeBall && this.activeBall.isValid) {
  1081. this.debugCheckNearBlocks();
  1082. }
  1083. }
  1084. /**
  1085. * 维持所有小球的恒定速度
  1086. */
  1087. private maintainAllBallsSpeed() {
  1088. // 维持主小球速度
  1089. if (this.activeBall && this.activeBall.isValid) {
  1090. this.maintainBallSpeed(this.activeBall);
  1091. }
  1092. // 维持额外小球的速度
  1093. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1094. if (gameArea) {
  1095. const additionalBalls = gameArea.children.filter(child =>
  1096. child.name === 'AdditionalBall' && child.isValid
  1097. );
  1098. for (const ball of additionalBalls) {
  1099. this.maintainBallSpeed(ball);
  1100. }
  1101. }
  1102. }
  1103. /**
  1104. * 维持单个小球的恒定速度
  1105. */
  1106. private maintainBallSpeed(ball: Node) {
  1107. const rigidBody = ball.getComponent(RigidBody2D);
  1108. if (!rigidBody) return;
  1109. // 获取当前速度
  1110. const currentVelocity = rigidBody.linearVelocity;
  1111. const speed = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
  1112. // 如果速度过低或过高,重新设置速度以维持恒定运动
  1113. if (speed < this.currentSpeed * 0.85 || speed > this.currentSpeed * 1.15) {
  1114. // 保持当前方向,但调整速度大小
  1115. if (speed > 0.1) {
  1116. const normalizedVelocity = currentVelocity.clone().normalize();
  1117. rigidBody.linearVelocity = new Vec2(
  1118. normalizedVelocity.x * this.currentSpeed,
  1119. normalizedVelocity.y * this.currentSpeed
  1120. );
  1121. } else {
  1122. // 如果速度几乎为0,给一个随机方向
  1123. const angle = Math.random() * Math.PI * 2;
  1124. rigidBody.linearVelocity = new Vec2(
  1125. Math.cos(angle) * this.currentSpeed,
  1126. Math.sin(angle) * this.currentSpeed
  1127. );
  1128. }
  1129. }
  1130. // 更新主小球的方向向量(用于其他逻辑)
  1131. if (ball === this.activeBall && speed > 1.0) {
  1132. this.direction.x = currentVelocity.x / speed;
  1133. this.direction.y = currentVelocity.y / speed;
  1134. }
  1135. }
  1136. // 调试方法:检查小球是否接近方块但没有触发物理碰撞
  1137. private debugCheckCounter = 0;
  1138. private debugCheckNearBlocks() {
  1139. this.debugCheckCounter++;
  1140. // 每60帧(约1秒)检查一次
  1141. if (this.debugCheckCounter % 60 !== 0) return;
  1142. const ballPos = this.activeBall.worldPosition;
  1143. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) return;
  1144. let nearestDistance = Infinity;
  1145. let nearestBlock = null;
  1146. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  1147. const block = this.placedBlocksContainer.children[i];
  1148. if (block.name.includes('Block') || block.getChildByName('B1')) {
  1149. const blockPos = block.worldPosition;
  1150. const distance = Math.sqrt(
  1151. Math.pow(ballPos.x - blockPos.x, 2) +
  1152. Math.pow(ballPos.y - blockPos.y, 2)
  1153. );
  1154. if (distance < nearestDistance) {
  1155. nearestDistance = distance;
  1156. nearestBlock = block;
  1157. }
  1158. }
  1159. }
  1160. if (nearestBlock && nearestDistance < 100) {
  1161. // 检查小球的碰撞体状态
  1162. const ballCollider = this.activeBall.getComponent(Collider2D);
  1163. if (ballCollider) {
  1164. if (ballCollider instanceof CircleCollider2D) {
  1165. // 小球碰撞半径检查
  1166. }
  1167. }
  1168. // 检查小球的刚体状态
  1169. const ballRigidBody = this.activeBall.getComponent(RigidBody2D);
  1170. if (ballRigidBody) {
  1171. // 刚体状态检查
  1172. }
  1173. // 检查最近的方块碰撞体
  1174. const blockCollider = nearestBlock.getComponent(Collider2D);
  1175. if (blockCollider) {
  1176. // 方块碰撞体检查
  1177. }
  1178. }
  1179. }
  1180. // 初始化方向
  1181. initializeDirection() {
  1182. // 随机初始方向
  1183. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  1184. this.direction.x = Math.cos(angle);
  1185. this.direction.y = Math.sin(angle);
  1186. this.direction.normalize();
  1187. // 设置初始速度
  1188. if (this.activeBall) {
  1189. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  1190. if (rigidBody) {
  1191. rigidBody.linearVelocity = new Vec2(
  1192. this.direction.x * this.currentSpeed,
  1193. this.direction.y * this.currentSpeed
  1194. );
  1195. }
  1196. }
  1197. }
  1198. // 初始化球的参数 - 公开方法,供GameManager调用
  1199. public initialize() {
  1200. this.calculateGameBounds();
  1201. this.createBall();
  1202. // 检查方块碰撞体(延迟执行,确保方块已放置)
  1203. this.scheduleOnce(() => {
  1204. this.checkBlockColliders();
  1205. }, 0.5);
  1206. }
  1207. // 启动小球 - 公开方法,在确定按钮点击后调用
  1208. public startBall() {
  1209. // 检查ballPrefab是否设置
  1210. if (!this.ballPrefab) {
  1211. console.error('[BallController] ballPrefab 未设置,无法创建小球');
  1212. return;
  1213. }
  1214. // 如果还没有初始化,先初始化
  1215. if (!this.initialized) {
  1216. this.initialize();
  1217. }
  1218. // 确保小球存在且有效
  1219. if (!this.activeBall || !this.activeBall.isValid) {
  1220. this.createBall();
  1221. }
  1222. // 检查小球是否成功创建
  1223. if (!this.activeBall) {
  1224. console.error('[BallController] 小球创建失败');
  1225. return;
  1226. }
  1227. // 重新定位小球,避免与方块重叠
  1228. this.positionBallRandomly();
  1229. // 确保物理组件设置正确
  1230. this.setupCollider();
  1231. // 初始化运动方向并开始运动
  1232. this.initializeDirection();
  1233. // 设置运动状态
  1234. this.ballStarted = true;
  1235. console.log('[BallController] 小球启动完成');
  1236. }
  1237. /**
  1238. * 暂停小球运动:记录当前速度并停止刚体
  1239. */
  1240. public pauseBall() {
  1241. if (this.isPaused) return;
  1242. this.isPaused = true;
  1243. this.ballStarted = false;
  1244. if (this.activeBall && this.activeBall.isValid) {
  1245. const rb = this.activeBall.getComponent(RigidBody2D);
  1246. if (rb) {
  1247. this.pausedVelocity = rb.linearVelocity.clone();
  1248. rb.linearVelocity = new Vec2(0, 0);
  1249. rb.sleep();
  1250. }
  1251. }
  1252. }
  1253. /**
  1254. * 恢复小球运动:恢复暂停前的速度
  1255. */
  1256. public resumeBall() {
  1257. if (!this.isPaused) return;
  1258. this.isPaused = false;
  1259. this.ballStarted = true;
  1260. console.log('恢复小球运动');
  1261. if (this.activeBall && this.activeBall.isValid) {
  1262. const rb = this.activeBall.getComponent(RigidBody2D);
  1263. if (rb) {
  1264. rb.wakeUp();
  1265. const hasPrevVelocity = this.pausedVelocity && (this.pausedVelocity.x !== 0 || this.pausedVelocity.y !== 0);
  1266. if (hasPrevVelocity) {
  1267. rb.linearVelocity = this.pausedVelocity.clone();
  1268. } else {
  1269. // 若没有记录速度,则重新初始化方向
  1270. this.initializeDirection();
  1271. }
  1272. }
  1273. }
  1274. }
  1275. /**
  1276. * 从给定世界坐标发射子弹
  1277. */
  1278. private fireBulletAt(blockNode: Node, fireWorldPos: Vec3) {
  1279. // 检查方块节点是否有效
  1280. if (!blockNode || !blockNode.isValid) {
  1281. return;
  1282. }
  1283. // 检查子弹预制体是否存在
  1284. if (!this.bulletPrefab) {
  1285. console.warn(`[BallController] 子弹预制体未设置,无法发射`);
  1286. return;
  1287. }
  1288. // 查找方块中的武器节点
  1289. const weaponNode = this.findWeaponNode(blockNode);
  1290. if (!weaponNode) {
  1291. const blockName = blockNode && blockNode.isValid ? blockNode.name : 'unknown';
  1292. console.warn(`[BallController] 方块 ${blockName} 中未找到武器节点`);
  1293. }
  1294. // 传递武器节点给createAndFireBullet方法
  1295. this.createAndFireBullet(fireWorldPos, weaponNode);
  1296. }
  1297. /**
  1298. * 重置球控制器状态 - 游戏重置时调用
  1299. */
  1300. public resetBallController() {
  1301. console.log('[BallController] 重置球控制器状态');
  1302. // 停止球的运动
  1303. this.ballStarted = false;
  1304. this.isPaused = false;
  1305. // 清理暂停状态
  1306. this.pausedVelocity = new Vec2();
  1307. // 销毁当前活动的球
  1308. if (this.activeBall && this.activeBall.isValid) {
  1309. console.log('[BallController] 销毁当前活动的球');
  1310. this.activeBall.destroy();
  1311. }
  1312. this.activeBall = null;
  1313. // 销毁所有额外创建的球
  1314. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1315. if (gameArea) {
  1316. const additionalBalls = gameArea.children.filter(child =>
  1317. child.name === 'AdditionalBall' && child.isValid
  1318. );
  1319. for (const ball of additionalBalls) {
  1320. console.log('[BallController] 销毁额外球:', ball.name);
  1321. ball.destroy();
  1322. }
  1323. if (additionalBalls.length > 0) {
  1324. console.log(`[BallController] 已清理 ${additionalBalls.length} 个额外球`);
  1325. }
  1326. }
  1327. // 重置初始化状态
  1328. this.initialized = false;
  1329. // 清理冷却时间
  1330. this.blockFireCooldown.clear();
  1331. // 清理防围困状态数据
  1332. this.ballHitHistory.clear();
  1333. this.ballPhaseThrough.clear();
  1334. this.ballDeflectionAttempts.clear();
  1335. // 重置球速
  1336. this.updateBallSpeed();
  1337. console.log('[BallController] 球控制器重置完成');
  1338. }
  1339. /**
  1340. * 清理过期的防围困状态
  1341. */
  1342. private cleanupExpiredAntiTrapStates() {
  1343. const currentTime = performance.now() / 1000;
  1344. // 清理过期的穿透状态
  1345. for (const [ballId, endTime] of this.ballPhaseThrough.entries()) {
  1346. if (currentTime >= endTime) {
  1347. this.ballPhaseThrough.delete(ballId);
  1348. }
  1349. }
  1350. // 检查并重置长时间未频繁撞击的球的偏移尝试次数
  1351. for (const [ballId, hitHistory] of this.ballHitHistory.entries()) {
  1352. // 如果撞击历史为空或最近一次撞击超过时间窗口的一半,重置偏移尝试次数
  1353. if (hitHistory.length === 0 ||
  1354. (hitHistory.length > 0 && currentTime - hitHistory[hitHistory.length - 1] > this.antiTrapTimeWindow / 2)) {
  1355. if (this.ballDeflectionAttempts.has(ballId)) {
  1356. this.ballDeflectionAttempts.set(ballId, 0);
  1357. }
  1358. }
  1359. }
  1360. }
  1361. /**
  1362. * 清理单个小球的防围困状态数据
  1363. * @param ballId 小球的唯一标识符
  1364. */
  1365. public cleanupBallAntiTrapState(ballId: string) {
  1366. this.ballHitHistory.delete(ballId);
  1367. this.ballPhaseThrough.delete(ballId);
  1368. this.ballDeflectionAttempts.delete(ballId);
  1369. console.log(`Cleaned up anti-trap state for ball ${ballId}`);
  1370. }
  1371. onDestroy() {
  1372. // 清理事件监听
  1373. const eventBus = EventBus.getInstance();
  1374. eventBus.off(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
  1375. eventBus.off(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  1376. eventBus.off(GameEvents.RESET_BALL_CONTROLLER, this.onResetBallControllerEvent, this);
  1377. // 清理物理事件监听器
  1378. const physics = PhysicsManager.getInstance()?.getSystem();
  1379. if (physics) {
  1380. physics.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  1381. }
  1382. // 清理防围困状态数据
  1383. this.ballHitHistory.clear();
  1384. this.ballPhaseThrough.clear();
  1385. this.ballDeflectionAttempts.clear();
  1386. }
  1387. private updateBallSpeed() {
  1388. const skillManager = PersistentSkillManager.getInstance();
  1389. if (skillManager) {
  1390. this.currentSpeed = skillManager.applyBallSpeedBonus(this.baseSpeed);
  1391. } else {
  1392. this.currentSpeed = this.baseSpeed;
  1393. }
  1394. }
  1395. }