BallController.ts 44 KB

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