BallController.ts 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  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. console.log('🎯 碰撞成功...');
  403. console.log('碰撞对象:', {
  404. self: selfCollider.node.name,
  405. other: otherCollider.node.name,
  406. otherGroup: otherCollider.group,
  407. selfGroup: selfCollider.group
  408. });
  409. // 判断哪个是小球,哪个是方块
  410. let ballNode: Node = null;
  411. let blockNode: Node = null;
  412. // 检查self是否为小球(组1)
  413. if (selfCollider.group === 1) {
  414. ballNode = selfCollider.node;
  415. blockNode = otherCollider.node;
  416. }
  417. // 检查other是否为小球(组1)
  418. else if (otherCollider.group === 1) {
  419. ballNode = otherCollider.node;
  420. blockNode = selfCollider.node;
  421. }
  422. // 如果没有找到小球,跳过处理
  423. if (!ballNode || !blockNode) {
  424. console.log('❌ 未检测到小球参与的碰撞');
  425. return;
  426. }
  427. console.log('✅ 检测到小球与方块碰撞:', {
  428. ball: ballNode.name,
  429. block: blockNode.name
  430. });
  431. // 检查碰撞对象是否为方块
  432. const nodeName = blockNode.name;
  433. const nodePath = this.getNodePath(blockNode);
  434. // 检查是否有Weapon子节点(判断是否为方块)
  435. const hasWeaponChild = blockNode.getChildByName('Weapon') !== null;
  436. const isBlock =
  437. nodeName.includes('Block') ||
  438. nodePath.includes('Block') ||
  439. hasWeaponChild;
  440. console.log('判定为方块:', isBlock);
  441. if (isBlock) {
  442. console.log(`🎯 检测到方块碰撞: ${nodeName}, 路径: ${nodePath}`);
  443. console.log('🚀 方块武器被激活,发射子弹攻击敌人...');
  444. // 计算碰撞世界坐标,默认用接触点
  445. let contactPos: Vec3 = null;
  446. if (contact && (contact as any).getWorldManifold) {
  447. const wm = (contact as any).getWorldManifold();
  448. if (wm && wm.points && wm.points.length > 0) {
  449. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  450. }
  451. }
  452. if (!contactPos) {
  453. contactPos = blockNode.worldPosition.clone();
  454. }
  455. const now = performance.now();
  456. const lastTime = this.blockFireCooldown.get(blockNode.uuid) || 0;
  457. if (now - lastTime > this.FIRE_COOLDOWN * 1000) {
  458. this.blockFireCooldown.set(blockNode.uuid, now);
  459. this.fireBulletAt(blockNode, contactPos);
  460. }
  461. }
  462. }
  463. // 碰撞结束事件 - 简化版本
  464. onEndContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  465. console.log('🔚 碰撞结束:', {
  466. self: selfCollider.node.name,
  467. other: otherCollider.node.name
  468. });
  469. }
  470. // 碰撞预处理事件 - 简化版本
  471. onPreSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  472. // console.log('⚙️ 碰撞预处理:', otherCollider.node.name);
  473. }
  474. // 碰撞后处理事件 - 简化版本
  475. onPostSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  476. // console.log('✅ 碰撞后处理:', otherCollider.node.name);
  477. }
  478. // 计算反射向量
  479. calculateReflection(direction: Vec2, normal: Vec2): Vec2 {
  480. // 使用反射公式: R = V - 2(V·N)N
  481. const dot = direction.x * normal.x + direction.y * normal.y;
  482. const reflection = new Vec2(
  483. direction.x - 2 * dot * normal.x,
  484. direction.y - 2 * dot * normal.y
  485. );
  486. reflection.normalize();
  487. // 添加一些随机性,避免重复的反弹路径
  488. const randomAngle = (Math.random() - 0.5) * this.maxReflectionRandomness; // 随机角度
  489. const cos = Math.cos(randomAngle);
  490. const sin = Math.sin(randomAngle);
  491. // 应用随机旋转
  492. const randomizedReflection = new Vec2(
  493. reflection.x * cos - reflection.y * sin,
  494. reflection.x * sin + reflection.y * cos
  495. );
  496. // 确保反射方向不会太接近水平或垂直方向
  497. // 这有助于避免球在水平或垂直方向上来回反弹
  498. const minAngleFromAxis = 0.1; // 约5.7度
  499. // 检查是否接近水平方向
  500. if (Math.abs(randomizedReflection.y) < minAngleFromAxis) {
  501. // 调整y分量,使其远离水平方向
  502. const sign = randomizedReflection.y >= 0 ? 1 : -1;
  503. randomizedReflection.y = sign * (minAngleFromAxis + Math.random() * 0.1);
  504. // 重新归一化
  505. randomizedReflection.normalize();
  506. }
  507. // 检查是否接近垂直方向
  508. if (Math.abs(randomizedReflection.x) < minAngleFromAxis) {
  509. // 调整x分量,使其远离垂直方向
  510. const sign = randomizedReflection.x >= 0 ? 1 : -1;
  511. randomizedReflection.x = sign * (minAngleFromAxis + Math.random() * 0.1);
  512. // 重新归一化
  513. randomizedReflection.normalize();
  514. }
  515. randomizedReflection.normalize();
  516. console.log('反射方向:', {
  517. original: direction,
  518. normal: normal,
  519. reflection: reflection,
  520. randomized: randomizedReflection
  521. });
  522. return randomizedReflection;
  523. }
  524. /**
  525. * 从方块武器发射子弹攻击敌人 - 重构版本
  526. * 现在直接创建子弹实例并使用BulletController的实例方法
  527. * @param blockNode 激活的方块节点
  528. */
  529. fireBullet(blockNode: Node) {
  530. console.log('🔫 === 方块武器发射子弹流程 ===');
  531. console.log('激活的方块:', blockNode.name);
  532. console.log('方块路径:', this.getNodePath(blockNode));
  533. // 检查子弹预制体是否存在
  534. if (!this.bulletPrefab) {
  535. console.error('❌ 子弹预制体未设置');
  536. return;
  537. }
  538. // 查找方块中的Weapon节点
  539. console.log('🔍 开始查找方块中的Weapon节点...');
  540. const weaponNode = this.findWeaponNode(blockNode);
  541. if (!weaponNode) {
  542. console.error('❌ 在方块中找不到Weapon节点:', blockNode.name);
  543. console.log('方块结构:');
  544. this.logNodeStructure(blockNode, 0);
  545. // 如果找不到Weapon节点,使用方块本身的位置作为发射位置
  546. console.log('🔧 使用方块本身作为发射位置');
  547. const blockWorldPos = blockNode.worldPosition;
  548. console.log('方块世界坐标:', blockWorldPos);
  549. // 直接创建子弹并设置位置
  550. this.createAndFireBullet(blockWorldPos);
  551. console.log('🔫 === 方块武器发射子弹流程结束 ===');
  552. return;
  553. }
  554. console.log('✅ 找到Weapon节点:', weaponNode.name);
  555. console.log('Weapon节点路径:', this.getNodePath(weaponNode));
  556. // 获取武器的世界坐标作为发射位置
  557. let firePosition: Vec3;
  558. try {
  559. firePosition = weaponNode.worldPosition;
  560. console.log('武器世界坐标:', firePosition);
  561. } catch (error) {
  562. console.error('❌ 获取武器坐标失败:', error);
  563. // 备用方案:使用方块坐标
  564. firePosition = blockNode.worldPosition;
  565. console.log('使用方块坐标作为备用:', firePosition);
  566. }
  567. // 创建并发射子弹
  568. console.log('🚀 创建子弹...');
  569. this.createAndFireBullet(firePosition);
  570. console.log('🔫 === 方块武器发射子弹流程结束 ===');
  571. }
  572. /**
  573. * 创建并发射子弹 - 安全版本
  574. * @param firePosition 发射位置(世界坐标)
  575. */
  576. private createAndFireBullet(firePosition: Vec3) {
  577. console.log('🔫 === 开始创建子弹(安全模式)===');
  578. // 创建子弹实例
  579. const bullet = instantiate(this.bulletPrefab);
  580. if (!bullet) {
  581. console.error('❌ 子弹实例创建失败');
  582. return;
  583. }
  584. console.log('✅ 子弹实例创建成功:', bullet.name);
  585. // 获取子弹控制器并设置发射位置
  586. const bulletController = bullet.getComponent(BulletController);
  587. if (!bulletController) {
  588. console.error('❌ 子弹预制体缺少BulletController组件');
  589. bullet.destroy();
  590. return;
  591. }
  592. // 查找GameArea
  593. const gameArea = find('Canvas/GameLevelUI/GameArea');
  594. if (!gameArea) {
  595. console.error('❌ 找不到GameArea节点');
  596. bullet.destroy();
  597. return;
  598. }
  599. // 计算放置位置(先转换为本地坐标,避免出现原点闪烁)
  600. const gameAreaTrans = gameArea.getComponent(UITransform);
  601. const localPos = gameAreaTrans ? gameAreaTrans.convertToNodeSpaceAR(firePosition) : new Vec3();
  602. // 在添加到场景之前,先禁用可能引起问题的物理组件
  603. const rigidBody = bullet.getComponent(RigidBody2D);
  604. const collider = bullet.getComponent(Collider2D);
  605. if (rigidBody) {
  606. rigidBody.enabled = false;
  607. }
  608. if (collider) {
  609. collider.enabled = false;
  610. }
  611. // 设置位置再添加到场景,避免视觉闪烁
  612. bullet.position = localPos;
  613. gameArea.addChild(bullet);
  614. // 设定发射位置供 BulletController 使用
  615. bulletController.setFirePosition(firePosition);
  616. // 延迟启用物理组件,确保 Box2D world 已就绪,避免 m_world 报错
  617. this.scheduleOnce(() => {
  618. if (!bullet || !bullet.isValid) return;
  619. if (rigidBody && rigidBody.isValid) {
  620. rigidBody.enabled = true;
  621. }
  622. if (collider && collider.isValid) {
  623. collider.enabled = true;
  624. }
  625. }, 0.05);
  626. console.log('✅ 子弹生成完毕并将在 0.05s 后激活物理组件');
  627. console.log('🔫 === 子弹创建完成 ===');
  628. }
  629. // 递归查找Weapon节点
  630. private findWeaponNode(node: Node): Node | null {
  631. console.log(`🔍 在节点 ${node.name} 中查找Weapon...`);
  632. // 先检查当前节点是否有Weapon子节点
  633. const weaponNode = node.getChildByName('Weapon');
  634. if (weaponNode) {
  635. console.log(`✅ 在 ${node.name} 中找到Weapon节点`);
  636. return weaponNode;
  637. }
  638. // 如果没有,递归检查所有子节点
  639. for (let i = 0; i < node.children.length; i++) {
  640. const child = node.children[i];
  641. console.log(` 🔍 检查子节点: ${child.name}`);
  642. const foundWeapon = this.findWeaponNode(child);
  643. if (foundWeapon) {
  644. console.log(`✅ 在 ${child.name} 的子节点中找到Weapon`);
  645. return foundWeapon;
  646. }
  647. }
  648. // 如果都没找到,返回null
  649. console.log(`❌ 在 ${node.name} 及其子节点中未找到Weapon`);
  650. return null;
  651. }
  652. // 辅助方法:打印节点结构
  653. private logNodeStructure(node: Node, depth: number) {
  654. const indent = ' '.repeat(depth);
  655. console.log(`${indent}${node.name}`);
  656. for (let i = 0; i < node.children.length; i++) {
  657. this.logNodeStructure(node.children[i], depth + 1);
  658. }
  659. }
  660. // 获取节点的完整路径
  661. private getNodePath(node: Node): string {
  662. let path = node.name;
  663. let current = node;
  664. while (current.parent) {
  665. current = current.parent;
  666. path = current.name + '/' + path;
  667. }
  668. return path;
  669. }
  670. update(dt: number) {
  671. // 只有当小球已启动时才执行运动逻辑
  672. if (!this.ballStarted || !this.initialized || !this.activeBall || !this.activeBall.isValid) {
  673. return;
  674. }
  675. // 使用刚体组件控制小球移动,而不是直接设置位置
  676. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  677. if (rigidBody) {
  678. // 获取当前速度并确保方向向量与实际速度方向一致
  679. const currentVelocity = rigidBody.linearVelocity;
  680. const speed = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
  681. // 确保方向向量与实际速度方向一致
  682. if (speed > 1.0) {
  683. this.direction.x = currentVelocity.x / speed;
  684. this.direction.y = currentVelocity.y / speed;
  685. }
  686. // 如果速度过低,重新设置速度以维持恒定运动
  687. if (speed < this.speed * 0.9) {
  688. rigidBody.linearVelocity = new Vec2(
  689. this.direction.x * this.speed,
  690. this.direction.y * this.speed
  691. );
  692. }
  693. // 定期检查小球是否接近方块但没有触发碰撞(调试用)
  694. this.debugCheckNearBlocks();
  695. }
  696. }
  697. // 调试方法:检查小球是否接近方块但没有触发物理碰撞
  698. private debugCheckCounter = 0;
  699. private debugCheckNearBlocks() {
  700. this.debugCheckCounter++;
  701. // 每60帧(约1秒)检查一次
  702. if (this.debugCheckCounter % 60 !== 0) return;
  703. const ballPos = this.activeBall.worldPosition;
  704. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) return;
  705. let nearestDistance = Infinity;
  706. let nearestBlock = null;
  707. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  708. const block = this.placedBlocksContainer.children[i];
  709. if (block.name.includes('Block') || block.getChildByName('B1')) {
  710. const blockPos = block.worldPosition;
  711. const distance = Math.sqrt(
  712. Math.pow(ballPos.x - blockPos.x, 2) +
  713. Math.pow(ballPos.y - blockPos.y, 2)
  714. );
  715. if (distance < nearestDistance) {
  716. nearestDistance = distance;
  717. nearestBlock = block;
  718. }
  719. }
  720. }
  721. if (nearestBlock && nearestDistance < 100) {
  722. console.log(`⚠️ 小球接近方块但无物理碰撞: 距离=${nearestDistance.toFixed(1)}, 方块=${nearestBlock.name}`);
  723. console.log('小球位置:', ballPos);
  724. console.log('方块位置:', nearestBlock.worldPosition);
  725. // 检查小球的碰撞体状态
  726. console.log('=== 小球碰撞体详细检查 ===');
  727. const ballCollider = this.activeBall.getComponent(Collider2D);
  728. console.log('小球有碰撞体:', !!ballCollider);
  729. if (ballCollider) {
  730. console.log('小球碰撞体类型:', ballCollider.constructor.name);
  731. console.log('小球碰撞组:', ballCollider.group);
  732. console.log('小球碰撞标签:', ballCollider.tag);
  733. console.log('小球是否为传感器:', ballCollider.sensor);
  734. console.log('小球碰撞体是否启用:', ballCollider.enabled);
  735. if (ballCollider instanceof CircleCollider2D) {
  736. console.log('小球碰撞半径:', ballCollider.radius);
  737. }
  738. }
  739. // 检查小球的刚体状态
  740. const ballRigidBody = this.activeBall.getComponent(RigidBody2D);
  741. console.log('小球有刚体:', !!ballRigidBody);
  742. if (ballRigidBody) {
  743. console.log('小球刚体类型:', ballRigidBody.type);
  744. console.log('小球刚体启用碰撞监听:', ballRigidBody.enabledContactListener);
  745. console.log('小球刚体是否启用:', ballRigidBody.enabled);
  746. }
  747. // 检查最近的方块碰撞体
  748. console.log('=== 方块碰撞体详细检查 ===');
  749. const blockCollider = nearestBlock.getComponent(Collider2D);
  750. console.log('方块有碰撞体:', !!blockCollider);
  751. if (blockCollider) {
  752. console.log('方块碰撞体类型:', blockCollider.constructor.name);
  753. console.log('方块碰撞组:', blockCollider.group);
  754. console.log('方块碰撞标签:', blockCollider.tag);
  755. console.log('方块是否为传感器:', blockCollider.sensor);
  756. console.log('方块碰撞体是否启用:', blockCollider.enabled);
  757. }
  758. // 检查碰撞矩阵
  759. console.log('=== 碰撞矩阵检查 ===');
  760. if (ballCollider && blockCollider) {
  761. console.log(`小球组${ballCollider.group} 是否能与方块组${blockCollider.group} 碰撞: ${this.checkCollisionMatrix(ballCollider.group, blockCollider.group)}`);
  762. }
  763. // 检查物理引擎状态
  764. console.log('=== 物理引擎状态检查 ===');
  765. console.log('物理引擎是否启用:', PhysicsManager.getInstance()?.getSystem().enable);
  766. console.log('物理引擎重力:', PhysicsManager.getInstance()?.getSystem().gravity);
  767. }
  768. }
  769. // 检查碰撞矩阵
  770. private checkCollisionMatrix(group1: number, group2: number): boolean {
  771. // 根据项目配置检查碰撞矩阵
  772. // "collisionMatrix": { "0": 3, "1": 39, "2": 6, "3": 16, "4": 40, "5": 18 }
  773. const collisionMatrix: { [key: string]: number } = {
  774. "0": 3,
  775. "1": 39,
  776. "2": 6,
  777. "3": 16,
  778. "4": 40,
  779. "5": 18
  780. };
  781. const mask1 = collisionMatrix[group1.toString()];
  782. const mask2 = collisionMatrix[group2.toString()];
  783. console.log(`组${group1}的碰撞掩码: ${mask1} (二进制: ${mask1?.toString(2)})`);
  784. console.log(`组${group2}的碰撞掩码: ${mask2} (二进制: ${mask2?.toString(2)})`);
  785. // 检查group1是否能与group2碰撞
  786. const canCollide1to2 = mask1 && (mask1 & (1 << group2)) !== 0;
  787. // 检查group2是否能与group1碰撞
  788. const canCollide2to1 = mask2 && (mask2 & (1 << group1)) !== 0;
  789. console.log(`组${group1}->组${group2}: ${canCollide1to2}`);
  790. console.log(`组${group2}->组${group1}: ${canCollide2to1}`);
  791. return canCollide1to2 && canCollide2to1;
  792. }
  793. // 初始化方向
  794. initializeDirection() {
  795. // 随机初始方向
  796. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  797. this.direction.x = Math.cos(angle);
  798. this.direction.y = Math.sin(angle);
  799. this.direction.normalize();
  800. console.log('Ball initialized with direction:', this.direction);
  801. // 设置初始速度
  802. if (this.activeBall) {
  803. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  804. if (rigidBody) {
  805. rigidBody.linearVelocity = new Vec2(
  806. this.direction.x * this.speed,
  807. this.direction.y * this.speed
  808. );
  809. console.log('Ball initial velocity set:', rigidBody.linearVelocity);
  810. } else {
  811. console.error('无法找到小球的RigidBody2D组件');
  812. }
  813. }
  814. }
  815. // 初始化球的参数 - 公开方法,供GameManager调用
  816. public initialize() {
  817. console.log('🎮 === BallController 初始化 ===');
  818. this.calculateGameBounds();
  819. this.createBall();
  820. // 检查方块碰撞体(延迟执行,确保方块已放置)
  821. this.scheduleOnce(() => {
  822. this.checkBlockColliders();
  823. }, 0.5);
  824. console.log('🎮 === BallController 初始化完成 ===');
  825. }
  826. // 启动小球 - 公开方法,在确定按钮点击后调用
  827. public startBall() {
  828. console.log('🚀 === 启动小球系统 ===');
  829. // 如果还没有初始化,先初始化
  830. if (!this.initialized) {
  831. this.initialize();
  832. }
  833. // 确保小球存在且有效
  834. if (!this.activeBall || !this.activeBall.isValid) {
  835. console.log('⚠️ 小球不存在,重新创建...');
  836. this.createBall();
  837. }
  838. // 重新定位小球,避免与方块重叠
  839. console.log('📍 重新定位小球位置...');
  840. this.positionBallRandomly();
  841. // 确保物理组件设置正确
  842. this.setupCollider();
  843. // 初始化运动方向并开始运动
  844. this.initializeDirection();
  845. // 设置运动状态
  846. this.ballStarted = true;
  847. console.log('🚀 === 小球系统启动完成,开始运动 ===');
  848. }
  849. // 输出碰撞矩阵调试信息
  850. private logCollisionMatrix() {
  851. // 根据项目配置检查碰撞矩阵
  852. // "collisionMatrix": { "0": 3, "1": 39, "2": 6, "3": 16, "4": 40, "5": 18 }
  853. const collisionMatrix: { [key: string]: number } = {
  854. "0": 3,
  855. "1": 39,
  856. "2": 6,
  857. "3": 16,
  858. "4": 40,
  859. "5": 18
  860. };
  861. console.log('🔍 === 碰撞矩阵配置 ===');
  862. for (const group in collisionMatrix) {
  863. const mask = collisionMatrix[group];
  864. console.log(`组 ${group}: 掩码 ${mask} (二进制: ${mask?.toString(2)})`);
  865. }
  866. // 测试Ball组(1)和Block组(2)是否能碰撞
  867. const ballMask = collisionMatrix["1"]; // 39
  868. const blockMask = collisionMatrix["2"]; // 6
  869. const ballCanCollideWithBlock = (ballMask & (1 << 2)) !== 0; // 检查Ball能否与组2碰撞
  870. const blockCanCollideWithBall = (blockMask & (1 << 1)) !== 0; // 检查Block能否与组1碰撞
  871. console.log('🎯 碰撞测试结果:');
  872. console.log(`Ball组(1) -> Block组(2): ${ballCanCollideWithBlock}`);
  873. console.log(`Block组(2) -> Ball组(1): ${blockCanCollideWithBall}`);
  874. console.log(`双向碰撞可用: ${ballCanCollideWithBlock && blockCanCollideWithBall}`);
  875. console.log('🔍 === 碰撞矩阵分析完成 ===');
  876. }
  877. /**
  878. * 从给定世界坐标发射子弹
  879. */
  880. private fireBulletAt(blockNode: Node, fireWorldPos: Vec3) {
  881. console.log('🔫 === 方块武器发射子弹流程 ===');
  882. console.log('激活的方块:', blockNode.name);
  883. console.log('方块路径:', this.getNodePath(blockNode));
  884. // 检查子弹预制体是否存在
  885. if (!this.bulletPrefab) {
  886. console.error('❌ 子弹预制体未设置');
  887. return;
  888. }
  889. // 直接使用碰撞世界坐标作为发射点
  890. this.createAndFireBullet(fireWorldPos);
  891. console.log('🔫 === 方块武器发射子弹流程结束 ===');
  892. }
  893. }