BallController.ts 40 KB

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