BallController.ts 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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.sensor = false;
  257. // 添加刚体组件
  258. let rigidBody = ball.getComponent(RigidBody2D);
  259. if (!rigidBody) {
  260. rigidBody = ball.addComponent(RigidBody2D);
  261. }
  262. // 设置刚体属性
  263. rigidBody.type = 2; // 2 = 动态刚体
  264. rigidBody.allowSleep = false;
  265. rigidBody.gravityScale = 0;
  266. rigidBody.linearDamping = 0;
  267. rigidBody.angularDamping = 0;
  268. rigidBody.fixedRotation = true;
  269. // 添加碰撞回调
  270. if (collider) {
  271. collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  272. }
  273. }
  274. // 为额外小球初始化方向和速度
  275. private initializeBallDirection(ball: Node) {
  276. // 随机初始方向
  277. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  278. const direction = new Vec2(Math.cos(angle), Math.sin(angle)).normalize();
  279. // 设置初始速度
  280. const rigidBody = ball.getComponent(RigidBody2D);
  281. if (rigidBody) {
  282. rigidBody.linearVelocity = new Vec2(
  283. direction.x * this.currentSpeed,
  284. direction.y * this.currentSpeed
  285. );
  286. }
  287. }
  288. // 检查所有已放置方块的碰撞体组件
  289. private checkBlockColliders() {
  290. if (!this.placedBlocksContainer) {
  291. return;
  292. }
  293. if (!this.placedBlocksContainer.isValid) {
  294. return;
  295. }
  296. const blocks = [];
  297. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  298. const block = this.placedBlocksContainer.children[i];
  299. if (block.name.includes('Block') || block.getChildByName('B1')) {
  300. blocks.push(block);
  301. }
  302. }
  303. let fixedCount = 0;
  304. for (let i = 0; i < blocks.length; i++) {
  305. const block = blocks[i];
  306. // 检查方块本身的碰撞体
  307. const blockCollider = block.getComponent(Collider2D);
  308. if (blockCollider) {
  309. // 🔧 自动修复碰撞组设置
  310. if (blockCollider.group !== 2) {
  311. blockCollider.group = 2; // 设置为Block组
  312. fixedCount++;
  313. }
  314. // 确保不是传感器
  315. if (blockCollider.sensor) {
  316. blockCollider.sensor = false;
  317. }
  318. }
  319. // 检查B1子节点的碰撞体
  320. const b1Node = block.getChildByName('B1');
  321. if (b1Node) {
  322. const b1Collider = b1Node.getComponent(Collider2D);
  323. if (b1Collider) {
  324. // 🔧 修复B1子节点的碰撞设置
  325. if (b1Collider.group !== 2) {
  326. b1Collider.group = 2; // 设置为Block组
  327. fixedCount++;
  328. }
  329. // 确保B1不是传感器(需要实际碰撞)
  330. if (b1Collider.sensor) {
  331. b1Collider.sensor = false;
  332. }
  333. }
  334. }
  335. // 检查Weapon子节点
  336. const weaponNode = this.findWeaponNode(block);
  337. if (weaponNode) {
  338. // 武器节点存在
  339. }
  340. }
  341. }
  342. // 随机位置小球
  343. positionBallRandomly() {
  344. if (!this.activeBall) return;
  345. const transform = this.activeBall.getComponent(UITransform);
  346. const ballRadius = transform ? transform.width / 2 : 25;
  347. // 计算可生成的范围(考虑小球半径,避免生成在边缘)
  348. const minX = this.gameBounds.left + ballRadius + 20; // 额外偏移,避免生成在边缘
  349. const maxX = this.gameBounds.right - ballRadius - 20;
  350. const minY = this.gameBounds.bottom + ballRadius + 20;
  351. const maxY = this.gameBounds.top - ballRadius - 20;
  352. // 获取GameArea节点
  353. const gameArea = find('Canvas/GameLevelUI/GameArea');
  354. if (!gameArea) {
  355. return;
  356. }
  357. // 查找PlacedBlocks节点,它包含所有放置的方块
  358. if (!this.placedBlocksContainer) {
  359. this.setRandomPositionDefault(minX, maxX, minY, maxY);
  360. return;
  361. }
  362. if (!this.placedBlocksContainer.isValid) {
  363. this.setRandomPositionDefault(minX, maxX, minY, maxY);
  364. return;
  365. }
  366. // 获取所有已放置的方块
  367. const placedBlocks = [];
  368. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  369. const block = this.placedBlocksContainer.children[i];
  370. // 检查是否是方块节点(通常以Block命名或有特定标识)
  371. if (block.name.includes('Block') || block.getChildByName('B1')) {
  372. placedBlocks.push(block);
  373. }
  374. }
  375. // 如果没有方块,使用默认随机位置
  376. if (placedBlocks.length === 0) {
  377. this.setRandomPositionDefault(minX, maxX, minY, maxY);
  378. return;
  379. }
  380. // 尝试找到一个不与任何方块重叠的位置
  381. let validPosition = false;
  382. let attempts = 0;
  383. const maxAttempts = 50; // 最大尝试次数
  384. let randomX, randomY;
  385. while (!validPosition && attempts < maxAttempts) {
  386. // 随机生成位置
  387. randomX = Math.random() * (maxX - minX) + minX;
  388. randomY = Math.random() * (maxY - minY) + minY;
  389. // 检查是否与任何方块重叠
  390. let overlapping = false;
  391. for (const block of placedBlocks) {
  392. // 获取方块的世界坐标
  393. const blockWorldPos = block.worldPosition;
  394. // 计算小球与方块的距离
  395. const distance = Math.sqrt(
  396. Math.pow(randomX - blockWorldPos.x, 2) +
  397. Math.pow(randomY - blockWorldPos.y, 2)
  398. );
  399. // 获取方块的尺寸
  400. const blockTransform = block.getComponent(UITransform);
  401. const blockSize = blockTransform ?
  402. Math.max(blockTransform.width, blockTransform.height) / 2 : 50;
  403. // 如果距离小于小球半径+方块尺寸的一半+安全距离,认为重叠
  404. const safeDistance = 20; // 额外安全距离
  405. if (distance < ballRadius + blockSize + safeDistance) {
  406. overlapping = true;
  407. break;
  408. }
  409. }
  410. // 如果没有重叠,找到了有效位置
  411. if (!overlapping) {
  412. validPosition = true;
  413. }
  414. attempts++;
  415. }
  416. // 如果找不到有效位置,使用默认位置(游戏区域底部中心)
  417. if (!validPosition) {
  418. randomX = (this.gameBounds.left + this.gameBounds.right) / 2;
  419. randomY = this.gameBounds.bottom + ballRadius + 50; // 底部上方50单位
  420. }
  421. // 将世界坐标转换为相对于GameArea的本地坐标
  422. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  423. this.activeBall.position = localPos;
  424. }
  425. // 设置默认随机位置
  426. setRandomPositionDefault(minX, maxX, minY, maxY) {
  427. // 随机生成位置
  428. const randomX = Math.random() * (maxX - minX) + minX;
  429. const randomY = Math.random() * (maxY - minY) + minY;
  430. // 将世界坐标转换为相对于GameArea的本地坐标
  431. const gameArea = find('Canvas/GameLevelUI/GameArea');
  432. if (gameArea) {
  433. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  434. this.activeBall.position = localPos;
  435. } else {
  436. // 直接设置位置(不太准确,但作为后备)
  437. this.activeBall.position = new Vec3(randomX - this.gameBounds.left, randomY - this.gameBounds.bottom, 0);
  438. }
  439. }
  440. // 设置碰撞组件
  441. setupCollider() {
  442. if (!this.activeBall) return;
  443. // 确保小球有刚体组件
  444. let rigidBody = this.activeBall.getComponent(RigidBody2D);
  445. if (!rigidBody) {
  446. rigidBody = this.activeBall.addComponent(RigidBody2D);
  447. rigidBody.type = 2; // Dynamic
  448. rigidBody.gravityScale = 0; // 不受重力影响
  449. rigidBody.enabledContactListener = true; // 启用碰撞监听
  450. rigidBody.fixedRotation = true; // 固定旋转
  451. rigidBody.allowSleep = false; // 不允许休眠
  452. rigidBody.linearDamping = 0; // 无线性阻尼,保持速度不衰减
  453. rigidBody.angularDamping = 0; // 无角阻尼
  454. } else {
  455. // 确保已有的刚体组件设置正确
  456. rigidBody.enabledContactListener = true;
  457. rigidBody.gravityScale = 0;
  458. rigidBody.linearDamping = 0; // 确保无线性阻尼,保持速度不衰减
  459. rigidBody.angularDamping = 0; // 确保无角阻尼
  460. rigidBody.allowSleep = false; // 不允许休眠
  461. }
  462. // 确保小球有碰撞组件
  463. let collider = this.activeBall.getComponent(CircleCollider2D);
  464. if (!collider) {
  465. collider = this.activeBall.addComponent(CircleCollider2D);
  466. collider.radius = this.radius || 25; // 使用已计算的半径或默认值
  467. collider.tag = 1; // 小球标签
  468. collider.group = 1; // 碰撞组1 - Ball组
  469. collider.sensor = false; // 非传感器(实际碰撞)
  470. collider.friction = 0; // 无摩擦
  471. collider.restitution = 1; // 完全弹性碰撞
  472. } else {
  473. // 确保已有的碰撞组件设置正确
  474. collider.sensor = false;
  475. collider.restitution = 1;
  476. collider.group = 1; // 确保是Ball组
  477. collider.tag = 1; // 确保标签正确
  478. }
  479. // === 使用全局回调监听器 ===
  480. const physics = PhysicsManager.getInstance()?.getSystem();
  481. if (physics) {
  482. // 先移除旧监听,避免重复注册
  483. physics.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  484. physics.off(Contact2DType.END_CONTACT, this.onEndContact, this);
  485. physics.off(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
  486. physics.off(Contact2DType.POST_SOLVE, this.onPostSolve, this);
  487. physics.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  488. physics.on(Contact2DType.END_CONTACT, this.onEndContact, this);
  489. physics.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
  490. physics.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
  491. }
  492. }
  493. // 碰撞回调 - 简化版本用于测试
  494. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  495. // Debug logs removed
  496. // 通过事件检查是否可以发射子弹
  497. const eventBus = EventBus.getInstance();
  498. let canFire = true;
  499. // 发送检查事件,如果有监听器返回false则不发射
  500. eventBus.emit(GameEvents.BALL_FIRE_BULLET, { canFire: (value: boolean) => { canFire = value; } });
  501. if (!canFire) {
  502. return;
  503. }
  504. // 判断哪个是小球,哪个是方块
  505. let ballNode: Node = null;
  506. let blockNode: Node = null;
  507. // 检查self是否为小球(组1)
  508. if (selfCollider.group === 1) {
  509. ballNode = selfCollider.node;
  510. blockNode = otherCollider.node;
  511. }
  512. // 检查other是否为小球(组1)
  513. else if (otherCollider.group === 1) {
  514. ballNode = otherCollider.node;
  515. blockNode = selfCollider.node;
  516. }
  517. // 如果没有找到小球,跳过处理
  518. if (!ballNode || !blockNode) {
  519. // Debug log removed
  520. return;
  521. }
  522. // 检查碰撞对象是否为方块
  523. const nodeName = blockNode.name;
  524. const nodePath = this.getNodePath(blockNode);
  525. // 检查是否有Weapon子节点(判断是否为方块)
  526. const hasWeaponChild = blockNode.getChildByName('Weapon') !== null;
  527. const isBlock =
  528. nodeName.includes('Block') ||
  529. nodePath.includes('Block') ||
  530. hasWeaponChild;
  531. if (isBlock) {
  532. // trigger bullet without verbose logging
  533. // 计算碰撞世界坐标,默认用接触点
  534. let contactPos: Vec3 = null;
  535. if (contact && (contact as any).getWorldManifold) {
  536. const wm = (contact as any).getWorldManifold();
  537. if (wm && wm.points && wm.points.length > 0) {
  538. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  539. }
  540. }
  541. if (!contactPos) {
  542. contactPos = blockNode.worldPosition.clone();
  543. }
  544. const now = performance.now();
  545. const lastTime = this.blockFireCooldown.get(blockNode.uuid) || 0;
  546. if (now - lastTime > this.FIRE_COOLDOWN * 1000) {
  547. this.blockFireCooldown.set(blockNode.uuid, now);
  548. this.fireBulletAt(blockNode, contactPos);
  549. }
  550. }
  551. }
  552. // 碰撞结束事件 - 简化版本
  553. onEndContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  554. // Debug log removed
  555. }
  556. // 碰撞预处理事件 - 简化版本
  557. onPreSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  558. // console.log('⚙️ 碰撞预处理:', otherCollider.node.name);
  559. }
  560. // 碰撞后处理事件 - 简化版本
  561. onPostSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  562. // console.log('✅ 碰撞后处理:', otherCollider.node.name);
  563. }
  564. // 计算反射向量
  565. calculateReflection(direction: Vec2, normal: Vec2): Vec2 {
  566. // 使用反射公式: R = V - 2(V·N)N
  567. const dot = direction.x * normal.x + direction.y * normal.y;
  568. const reflection = new Vec2(
  569. direction.x - 2 * dot * normal.x,
  570. direction.y - 2 * dot * normal.y
  571. );
  572. reflection.normalize();
  573. // 添加一些随机性,避免重复的反弹路径
  574. const randomAngle = (Math.random() - 0.5) * this.maxReflectionRandomness; // 随机角度
  575. const cos = Math.cos(randomAngle);
  576. const sin = Math.sin(randomAngle);
  577. // 应用随机旋转
  578. const randomizedReflection = new Vec2(
  579. reflection.x * cos - reflection.y * sin,
  580. reflection.x * sin + reflection.y * cos
  581. );
  582. // 确保反射方向不会太接近水平或垂直方向
  583. // 这有助于避免球在水平或垂直方向上来回反弹
  584. const minAngleFromAxis = 0.1; // 约5.7度
  585. // 检查是否接近水平方向
  586. if (Math.abs(randomizedReflection.y) < minAngleFromAxis) {
  587. // 调整y分量,使其远离水平方向
  588. const sign = randomizedReflection.y >= 0 ? 1 : -1;
  589. randomizedReflection.y = sign * (minAngleFromAxis + Math.random() * 0.1);
  590. // 重新归一化
  591. randomizedReflection.normalize();
  592. }
  593. // 检查是否接近垂直方向
  594. if (Math.abs(randomizedReflection.x) < minAngleFromAxis) {
  595. // 调整x分量,使其远离垂直方向
  596. const sign = randomizedReflection.x >= 0 ? 1 : -1;
  597. randomizedReflection.x = sign * (minAngleFromAxis + Math.random() * 0.1);
  598. // 重新归一化
  599. randomizedReflection.normalize();
  600. }
  601. randomizedReflection.normalize();
  602. // Debug log removed
  603. return randomizedReflection;
  604. }
  605. /**
  606. * 从方块武器发射子弹攻击敌人 - 重构版本
  607. * 现在直接创建子弹实例并使用BulletController的实例方法
  608. * @param blockNode 激活的方块节点
  609. */
  610. fireBullet(blockNode: Node) {
  611. // Debug logs removed
  612. // 检查子弹预制体是否存在
  613. if (!this.bulletPrefab) {
  614. return;
  615. }
  616. // 查找方块中的Weapon节点
  617. const weaponNode = this.findWeaponNode(blockNode);
  618. if (!weaponNode) {
  619. const blockWorldPos = blockNode.worldPosition;
  620. const weaponConfig2: WeaponConfig | null = (blockNode as any)['weaponConfig'] || null;
  621. this.createAndFireBullet(blockWorldPos, weaponConfig2);
  622. return;
  623. }
  624. // 获取武器的世界坐标作为发射位置
  625. let firePosition: Vec3;
  626. try {
  627. firePosition = weaponNode.worldPosition;
  628. } catch (error) {
  629. // 备用方案:使用方块坐标
  630. firePosition = blockNode.worldPosition;
  631. }
  632. // 创建并发射子弹
  633. const weaponConfig: WeaponConfig | null = (blockNode as any)['weaponConfig'] || null;
  634. this.createAndFireBullet(firePosition, weaponConfig);
  635. }
  636. /**
  637. * 创建并发射子弹 - 使用新的WeaponBullet系统
  638. * @param firePosition 发射位置(世界坐标)
  639. * @param weaponConfig 武器配置
  640. */
  641. private createAndFireBullet(firePosition: Vec3, weaponConfig: WeaponConfig | null) {
  642. // 确保武器配置加载
  643. WeaponBullet.loadWeaponsData().then(() => {
  644. // 默认使用毛豆射手配置,后续可以根据方块类型动态选择
  645. const defaultWeaponId = 'pea_shooter';
  646. const finalConfig = weaponConfig || WeaponBullet.getWeaponConfig(defaultWeaponId);
  647. if (!finalConfig) {
  648. return;
  649. }
  650. // 创建子弹初始化数据
  651. const initData: BulletInitData = {
  652. weaponId: finalConfig.id,
  653. firePosition: firePosition,
  654. autoTarget: true,
  655. weaponConfig: finalConfig
  656. };
  657. // 验证初始化数据
  658. if (!WeaponBullet.validateInitData(initData)) {
  659. return;
  660. }
  661. // 判断是否为多发子弹(散射/连发等)
  662. const countCfg = finalConfig.bulletConfig.count;
  663. const isMultiShot = countCfg && countCfg.type !== 'single' && countCfg.amount > 1;
  664. // 查找GameArea(子弹统一添加到此节点)
  665. const gameArea = find('Canvas/GameLevelUI/GameArea');
  666. if (!gameArea) {
  667. return;
  668. }
  669. // === 根据武器配置选择合适的预制体 ===
  670. const needsTrail = !!(finalConfig.bulletConfig?.visual?.trailEffect);
  671. const prefabToUse: Prefab = (needsTrail && this.bulletContainerPrefab) ? this.bulletContainerPrefab : this.bulletPrefab;
  672. if (!prefabToUse) {
  673. return; // 如果没有可用的预制体则直接退出
  674. }
  675. if (isMultiShot) {
  676. // 使用批量创建逻辑
  677. const bullets = WeaponBullet.createBullets(initData, prefabToUse as any);
  678. bullets.forEach(b => {
  679. gameArea.addChild(b);
  680. });
  681. } else {
  682. // 单发逻辑(沿用原流程)
  683. const bullet = instantiate(prefabToUse);
  684. if (!bullet) {
  685. return;
  686. }
  687. gameArea.addChild(bullet);
  688. let weaponBullet = bullet.getComponent(WeaponBullet);
  689. if (!weaponBullet) {
  690. weaponBullet = bullet.addComponent(WeaponBullet);
  691. }
  692. weaponBullet.init(initData);
  693. }
  694. }).catch(error => {
  695. // 武器配置加载失败
  696. });
  697. }
  698. // 递归查找Weapon节点
  699. private findWeaponNode(node: Node): Node | null {
  700. // logs removed
  701. // 先检查当前节点是否有Weapon子节点
  702. const weaponNode = node.getChildByName('Weapon');
  703. if (weaponNode) {
  704. return weaponNode;
  705. }
  706. // 如果没有,递归检查所有子节点
  707. for (let i = 0; i < node.children.length; i++) {
  708. const child = node.children[i];
  709. const foundWeapon = this.findWeaponNode(child);
  710. if (foundWeapon) {
  711. return foundWeapon;
  712. }
  713. }
  714. // 如果都没找到,返回null
  715. return null;
  716. }
  717. // 获取节点的完整路径
  718. private getNodePath(node: Node): string {
  719. let path = node.name;
  720. let current = node;
  721. while (current.parent) {
  722. current = current.parent;
  723. path = current.name + '/' + path;
  724. }
  725. return path;
  726. }
  727. update(dt: number) {
  728. // 只有当小球已启动时才执行运动逻辑
  729. if (!this.ballStarted || !this.initialized || !this.activeBall || !this.activeBall.isValid) {
  730. return;
  731. }
  732. // 使用刚体组件控制小球移动,而不是直接设置位置
  733. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  734. if (rigidBody) {
  735. // 获取当前速度并确保方向向量与实际速度方向一致
  736. const currentVelocity = rigidBody.linearVelocity;
  737. const speed = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
  738. // 确保方向向量与实际速度方向一致
  739. if (speed > 1.0) {
  740. this.direction.x = currentVelocity.x / speed;
  741. this.direction.y = currentVelocity.y / speed;
  742. }
  743. // 如果速度过低,重新设置速度以维持恒定运动
  744. if (speed < this.currentSpeed * 0.9) {
  745. rigidBody.linearVelocity = new Vec2(
  746. this.direction.x * this.currentSpeed,
  747. this.direction.y * this.currentSpeed
  748. );
  749. }
  750. // 定期检查小球是否接近方块但没有触发碰撞(调试用)
  751. this.debugCheckNearBlocks();
  752. }
  753. }
  754. // 调试方法:检查小球是否接近方块但没有触发物理碰撞
  755. private debugCheckCounter = 0;
  756. private debugCheckNearBlocks() {
  757. this.debugCheckCounter++;
  758. // 每60帧(约1秒)检查一次
  759. if (this.debugCheckCounter % 60 !== 0) return;
  760. const ballPos = this.activeBall.worldPosition;
  761. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) return;
  762. let nearestDistance = Infinity;
  763. let nearestBlock = null;
  764. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  765. const block = this.placedBlocksContainer.children[i];
  766. if (block.name.includes('Block') || block.getChildByName('B1')) {
  767. const blockPos = block.worldPosition;
  768. const distance = Math.sqrt(
  769. Math.pow(ballPos.x - blockPos.x, 2) +
  770. Math.pow(ballPos.y - blockPos.y, 2)
  771. );
  772. if (distance < nearestDistance) {
  773. nearestDistance = distance;
  774. nearestBlock = block;
  775. }
  776. }
  777. }
  778. if (nearestBlock && nearestDistance < 100) {
  779. // 检查小球的碰撞体状态
  780. const ballCollider = this.activeBall.getComponent(Collider2D);
  781. if (ballCollider) {
  782. if (ballCollider instanceof CircleCollider2D) {
  783. // 小球碰撞半径检查
  784. }
  785. }
  786. // 检查小球的刚体状态
  787. const ballRigidBody = this.activeBall.getComponent(RigidBody2D);
  788. if (ballRigidBody) {
  789. // 刚体状态检查
  790. }
  791. // 检查最近的方块碰撞体
  792. const blockCollider = nearestBlock.getComponent(Collider2D);
  793. if (blockCollider) {
  794. // 方块碰撞体检查
  795. }
  796. }
  797. }
  798. // 初始化方向
  799. initializeDirection() {
  800. // 随机初始方向
  801. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  802. this.direction.x = Math.cos(angle);
  803. this.direction.y = Math.sin(angle);
  804. this.direction.normalize();
  805. // 设置初始速度
  806. if (this.activeBall) {
  807. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  808. if (rigidBody) {
  809. rigidBody.linearVelocity = new Vec2(
  810. this.direction.x * this.currentSpeed,
  811. this.direction.y * this.currentSpeed
  812. );
  813. }
  814. }
  815. }
  816. // 初始化球的参数 - 公开方法,供GameManager调用
  817. public initialize() {
  818. this.calculateGameBounds();
  819. this.createBall();
  820. // 检查方块碰撞体(延迟执行,确保方块已放置)
  821. this.scheduleOnce(() => {
  822. this.checkBlockColliders();
  823. }, 0.5);
  824. }
  825. // 启动小球 - 公开方法,在确定按钮点击后调用
  826. public startBall() {
  827. // 检查ballPrefab是否设置
  828. if (!this.ballPrefab) {
  829. console.error('[BallController] ballPrefab 未设置,无法创建小球');
  830. return;
  831. }
  832. // 如果还没有初始化,先初始化
  833. if (!this.initialized) {
  834. this.initialize();
  835. }
  836. // 确保小球存在且有效
  837. if (!this.activeBall || !this.activeBall.isValid) {
  838. this.createBall();
  839. }
  840. // 检查小球是否成功创建
  841. if (!this.activeBall) {
  842. console.error('[BallController] 小球创建失败');
  843. return;
  844. }
  845. // 重新定位小球,避免与方块重叠
  846. this.positionBallRandomly();
  847. // 确保物理组件设置正确
  848. this.setupCollider();
  849. // 初始化运动方向并开始运动
  850. this.initializeDirection();
  851. // 设置运动状态
  852. this.ballStarted = true;
  853. console.log('[BallController] 小球启动完成');
  854. }
  855. /**
  856. * 暂停小球运动:记录当前速度并停止刚体
  857. */
  858. public pauseBall() {
  859. if (this.isPaused) return;
  860. this.isPaused = true;
  861. this.ballStarted = false;
  862. if (this.activeBall && this.activeBall.isValid) {
  863. const rb = this.activeBall.getComponent(RigidBody2D);
  864. if (rb) {
  865. this.pausedVelocity = rb.linearVelocity.clone();
  866. rb.linearVelocity = new Vec2(0, 0);
  867. rb.sleep();
  868. }
  869. }
  870. }
  871. /**
  872. * 恢复小球运动:恢复暂停前的速度
  873. */
  874. public resumeBall() {
  875. if (!this.isPaused) return;
  876. this.isPaused = false;
  877. this.ballStarted = true;
  878. console.log('恢复小球运动');
  879. if (this.activeBall && this.activeBall.isValid) {
  880. const rb = this.activeBall.getComponent(RigidBody2D);
  881. if (rb) {
  882. rb.wakeUp();
  883. const hasPrevVelocity = this.pausedVelocity && (this.pausedVelocity.x !== 0 || this.pausedVelocity.y !== 0);
  884. if (hasPrevVelocity) {
  885. rb.linearVelocity = this.pausedVelocity.clone();
  886. } else {
  887. // 若没有记录速度,则重新初始化方向
  888. this.initializeDirection();
  889. }
  890. }
  891. }
  892. }
  893. /**
  894. * 从给定世界坐标发射子弹
  895. */
  896. private fireBulletAt(blockNode: Node, fireWorldPos: Vec3) {
  897. // 检查子弹预制体是否存在
  898. if (!this.bulletPrefab) {
  899. return;
  900. }
  901. // 直接使用碰撞世界坐标作为发射点
  902. const weaponConfig: WeaponConfig | null = (blockNode as any)['weaponConfig'] || null;
  903. this.createAndFireBullet(fireWorldPos, weaponConfig);
  904. }
  905. /**
  906. * 重置球控制器状态 - 游戏重置时调用
  907. */
  908. public resetBallController() {
  909. console.log('[BallController] 重置球控制器状态');
  910. // 停止球的运动
  911. this.ballStarted = false;
  912. this.isPaused = false;
  913. // 清理暂停状态
  914. this.pausedVelocity = new Vec2();
  915. // 销毁当前活动的球
  916. if (this.activeBall && this.activeBall.isValid) {
  917. console.log('[BallController] 销毁当前活动的球');
  918. this.activeBall.destroy();
  919. }
  920. this.activeBall = null;
  921. // 重置初始化状态
  922. this.initialized = false;
  923. // 清理冷却时间
  924. this.blockFireCooldown.clear();
  925. // 重置球速
  926. this.updateBallSpeed();
  927. console.log('[BallController] 球控制器重置完成');
  928. }
  929. onDestroy() {
  930. // 清理事件监听
  931. const eventBus = EventBus.getInstance();
  932. eventBus.off(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
  933. eventBus.off(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  934. eventBus.off(GameEvents.RESET_BALL_CONTROLLER, this.onResetBallControllerEvent, this);
  935. }
  936. private updateBallSpeed() {
  937. const skillManager = PersistentSkillManager.getInstance();
  938. if (skillManager) {
  939. this.currentSpeed = skillManager.applyBallSpeedBonus(this.baseSpeed);
  940. } else {
  941. this.currentSpeed = this.baseSpeed;
  942. }
  943. }
  944. }