BallController.ts 42 KB

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