BallController.ts 36 KB

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