BallController.ts 42 KB

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