BallController.ts 45 KB

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