BallController.ts 39 KB

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