BallController.ts 57 KB

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