BallController.ts 67 KB

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