BallController.ts 44 KB

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