BallController.ts 37 KB

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