BallController.ts 41 KB

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