BallController.ts 40 KB

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