BallController.ts 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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. if (PhysicsSystem2D.instance) {
  384. // 先移除旧监听,避免重复注册
  385. PhysicsSystem2D.instance.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  386. PhysicsSystem2D.instance.off(Contact2DType.END_CONTACT, this.onEndContact, this);
  387. PhysicsSystem2D.instance.off(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
  388. PhysicsSystem2D.instance.off(Contact2DType.POST_SOLVE, this.onPostSolve, this);
  389. PhysicsSystem2D.instance.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  390. PhysicsSystem2D.instance.on(Contact2DType.END_CONTACT, this.onEndContact, this);
  391. PhysicsSystem2D.instance.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
  392. PhysicsSystem2D.instance.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
  393. console.log('✅ 已注册全局碰撞监听器');
  394. }
  395. console.log('✅ 小球碰撞组件设置完成');
  396. console.log('⚙️ === 碰撞组件设置完成 ===');
  397. }
  398. // 碰撞回调 - 简化版本用于测试
  399. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  400. console.log('🎯 碰撞成功...');
  401. console.log('碰撞对象:', {
  402. self: selfCollider.node.name,
  403. other: otherCollider.node.name,
  404. otherGroup: otherCollider.group,
  405. selfGroup: selfCollider.group
  406. });
  407. // 判断哪个是小球,哪个是方块
  408. let ballNode: Node = null;
  409. let blockNode: Node = null;
  410. // 检查self是否为小球(组1)
  411. if (selfCollider.group === 1) {
  412. ballNode = selfCollider.node;
  413. blockNode = otherCollider.node;
  414. }
  415. // 检查other是否为小球(组1)
  416. else if (otherCollider.group === 1) {
  417. ballNode = otherCollider.node;
  418. blockNode = selfCollider.node;
  419. }
  420. // 如果没有找到小球,跳过处理
  421. if (!ballNode || !blockNode) {
  422. console.log('❌ 未检测到小球参与的碰撞');
  423. return;
  424. }
  425. console.log('✅ 检测到小球与方块碰撞:', {
  426. ball: ballNode.name,
  427. block: blockNode.name
  428. });
  429. // 检查碰撞对象是否为方块
  430. const nodeName = blockNode.name;
  431. const nodePath = this.getNodePath(blockNode);
  432. // 检查是否有Weapon子节点(判断是否为方块)
  433. const hasWeaponChild = blockNode.getChildByName('Weapon') !== null;
  434. const isBlock =
  435. nodeName.includes('Block') ||
  436. nodePath.includes('Block') ||
  437. hasWeaponChild;
  438. console.log('判定为方块:', isBlock);
  439. if (isBlock) {
  440. console.log(`🎯 检测到方块碰撞: ${nodeName}, 路径: ${nodePath}`);
  441. console.log('🚀 方块武器被激活,发射子弹攻击敌人...');
  442. // 计算碰撞世界坐标,默认用接触点
  443. let contactPos: Vec3 = null;
  444. if (contact && (contact as any).getWorldManifold) {
  445. const wm = (contact as any).getWorldManifold();
  446. if (wm && wm.points && wm.points.length > 0) {
  447. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  448. }
  449. }
  450. if (!contactPos) {
  451. contactPos = blockNode.worldPosition.clone();
  452. }
  453. const now = performance.now();
  454. const lastTime = this.blockFireCooldown.get(blockNode.uuid) || 0;
  455. if (now - lastTime > this.FIRE_COOLDOWN * 1000) {
  456. this.blockFireCooldown.set(blockNode.uuid, now);
  457. this.fireBulletAt(blockNode, contactPos);
  458. }
  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 bulletController = bullet.getComponent(BulletController);
  585. if (!bulletController) {
  586. console.error('❌ 子弹预制体缺少BulletController组件');
  587. bullet.destroy();
  588. return;
  589. }
  590. // 查找GameArea
  591. const gameArea = find('Canvas/GameLevelUI/GameArea');
  592. if (!gameArea) {
  593. console.error('❌ 找不到GameArea节点');
  594. bullet.destroy();
  595. return;
  596. }
  597. // 计算放置位置(先转换为本地坐标,避免出现原点闪烁)
  598. const gameAreaTrans = gameArea.getComponent(UITransform);
  599. const localPos = gameAreaTrans ? gameAreaTrans.convertToNodeSpaceAR(firePosition) : new Vec3();
  600. // 在添加到场景之前,先禁用可能引起问题的物理组件
  601. const rigidBody = bullet.getComponent(RigidBody2D);
  602. const collider = bullet.getComponent(Collider2D);
  603. if (rigidBody) {
  604. rigidBody.enabled = false;
  605. }
  606. if (collider) {
  607. collider.enabled = false;
  608. }
  609. // 设置位置再添加到场景,避免视觉闪烁
  610. bullet.position = localPos;
  611. gameArea.addChild(bullet);
  612. // 设定发射位置供 BulletController 使用
  613. bulletController.setFirePosition(firePosition);
  614. // 延迟启用物理组件,确保 Box2D world 已就绪,避免 m_world 报错
  615. this.scheduleOnce(() => {
  616. if (!bullet || !bullet.isValid) return;
  617. if (rigidBody && rigidBody.isValid) {
  618. rigidBody.enabled = true;
  619. }
  620. if (collider && collider.isValid) {
  621. collider.enabled = true;
  622. }
  623. }, 0.05);
  624. console.log('✅ 子弹生成完毕并将在 0.05s 后激活物理组件');
  625. console.log('🔫 === 子弹创建完成 ===');
  626. }
  627. // 递归查找Weapon节点
  628. private findWeaponNode(node: Node): Node | null {
  629. console.log(`🔍 在节点 ${node.name} 中查找Weapon...`);
  630. // 先检查当前节点是否有Weapon子节点
  631. const weaponNode = node.getChildByName('Weapon');
  632. if (weaponNode) {
  633. console.log(`✅ 在 ${node.name} 中找到Weapon节点`);
  634. return weaponNode;
  635. }
  636. // 如果没有,递归检查所有子节点
  637. for (let i = 0; i < node.children.length; i++) {
  638. const child = node.children[i];
  639. console.log(` 🔍 检查子节点: ${child.name}`);
  640. const foundWeapon = this.findWeaponNode(child);
  641. if (foundWeapon) {
  642. console.log(`✅ 在 ${child.name} 的子节点中找到Weapon`);
  643. return foundWeapon;
  644. }
  645. }
  646. // 如果都没找到,返回null
  647. console.log(`❌ 在 ${node.name} 及其子节点中未找到Weapon`);
  648. return null;
  649. }
  650. // 辅助方法:打印节点结构
  651. private logNodeStructure(node: Node, depth: number) {
  652. const indent = ' '.repeat(depth);
  653. console.log(`${indent}${node.name}`);
  654. for (let i = 0; i < node.children.length; i++) {
  655. this.logNodeStructure(node.children[i], depth + 1);
  656. }
  657. }
  658. // 获取节点的完整路径
  659. private getNodePath(node: Node): string {
  660. let path = node.name;
  661. let current = node;
  662. while (current.parent) {
  663. current = current.parent;
  664. path = current.name + '/' + path;
  665. }
  666. return path;
  667. }
  668. update(dt: number) {
  669. // 只有当小球已启动时才执行运动逻辑
  670. if (!this.ballStarted || !this.initialized || !this.activeBall || !this.activeBall.isValid) {
  671. return;
  672. }
  673. // 使用刚体组件控制小球移动,而不是直接设置位置
  674. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  675. if (rigidBody) {
  676. // 获取当前速度并确保方向向量与实际速度方向一致
  677. const currentVelocity = rigidBody.linearVelocity;
  678. const speed = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
  679. // 确保方向向量与实际速度方向一致
  680. if (speed > 1.0) {
  681. this.direction.x = currentVelocity.x / speed;
  682. this.direction.y = currentVelocity.y / speed;
  683. }
  684. // 如果速度过低,重新设置速度以维持恒定运动
  685. if (speed < this.speed * 0.9) {
  686. rigidBody.linearVelocity = new Vec2(
  687. this.direction.x * this.speed,
  688. this.direction.y * this.speed
  689. );
  690. }
  691. // 定期检查小球是否接近方块但没有触发碰撞(调试用)
  692. this.debugCheckNearBlocks();
  693. }
  694. }
  695. // 调试方法:检查小球是否接近方块但没有触发物理碰撞
  696. private debugCheckCounter = 0;
  697. private debugCheckNearBlocks() {
  698. this.debugCheckCounter++;
  699. // 每60帧(约1秒)检查一次
  700. if (this.debugCheckCounter % 60 !== 0) return;
  701. const ballPos = this.activeBall.worldPosition;
  702. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) return;
  703. let nearestDistance = Infinity;
  704. let nearestBlock = null;
  705. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  706. const block = this.placedBlocksContainer.children[i];
  707. if (block.name.includes('Block') || block.getChildByName('B1')) {
  708. const blockPos = block.worldPosition;
  709. const distance = Math.sqrt(
  710. Math.pow(ballPos.x - blockPos.x, 2) +
  711. Math.pow(ballPos.y - blockPos.y, 2)
  712. );
  713. if (distance < nearestDistance) {
  714. nearestDistance = distance;
  715. nearestBlock = block;
  716. }
  717. }
  718. }
  719. if (nearestBlock && nearestDistance < 100) {
  720. console.log(`⚠️ 小球接近方块但无物理碰撞: 距离=${nearestDistance.toFixed(1)}, 方块=${nearestBlock.name}`);
  721. console.log('小球位置:', ballPos);
  722. console.log('方块位置:', nearestBlock.worldPosition);
  723. // 检查小球的碰撞体状态
  724. console.log('=== 小球碰撞体详细检查 ===');
  725. const ballCollider = this.activeBall.getComponent(Collider2D);
  726. console.log('小球有碰撞体:', !!ballCollider);
  727. if (ballCollider) {
  728. console.log('小球碰撞体类型:', ballCollider.constructor.name);
  729. console.log('小球碰撞组:', ballCollider.group);
  730. console.log('小球碰撞标签:', ballCollider.tag);
  731. console.log('小球是否为传感器:', ballCollider.sensor);
  732. console.log('小球碰撞体是否启用:', ballCollider.enabled);
  733. if (ballCollider instanceof CircleCollider2D) {
  734. console.log('小球碰撞半径:', ballCollider.radius);
  735. }
  736. }
  737. // 检查小球的刚体状态
  738. const ballRigidBody = this.activeBall.getComponent(RigidBody2D);
  739. console.log('小球有刚体:', !!ballRigidBody);
  740. if (ballRigidBody) {
  741. console.log('小球刚体类型:', ballRigidBody.type);
  742. console.log('小球刚体启用碰撞监听:', ballRigidBody.enabledContactListener);
  743. console.log('小球刚体是否启用:', ballRigidBody.enabled);
  744. }
  745. // 检查最近的方块碰撞体
  746. console.log('=== 方块碰撞体详细检查 ===');
  747. const blockCollider = nearestBlock.getComponent(Collider2D);
  748. console.log('方块有碰撞体:', !!blockCollider);
  749. if (blockCollider) {
  750. console.log('方块碰撞体类型:', blockCollider.constructor.name);
  751. console.log('方块碰撞组:', blockCollider.group);
  752. console.log('方块碰撞标签:', blockCollider.tag);
  753. console.log('方块是否为传感器:', blockCollider.sensor);
  754. console.log('方块碰撞体是否启用:', blockCollider.enabled);
  755. }
  756. // 检查碰撞矩阵
  757. console.log('=== 碰撞矩阵检查 ===');
  758. if (ballCollider && blockCollider) {
  759. console.log(`小球组${ballCollider.group} 是否能与方块组${blockCollider.group} 碰撞: ${this.checkCollisionMatrix(ballCollider.group, blockCollider.group)}`);
  760. }
  761. // 检查物理引擎状态
  762. console.log('=== 物理引擎状态检查 ===');
  763. console.log('物理引擎是否启用:', PhysicsSystem2D.instance.enable);
  764. console.log('物理引擎重力:', PhysicsSystem2D.instance.gravity);
  765. }
  766. }
  767. // 检查碰撞矩阵
  768. private checkCollisionMatrix(group1: number, group2: number): boolean {
  769. // 根据项目配置检查碰撞矩阵
  770. // "collisionMatrix": { "0": 3, "1": 39, "2": 6, "3": 16, "4": 40, "5": 18 }
  771. const collisionMatrix: { [key: string]: number } = {
  772. "0": 3,
  773. "1": 39,
  774. "2": 6,
  775. "3": 16,
  776. "4": 40,
  777. "5": 18
  778. };
  779. const mask1 = collisionMatrix[group1.toString()];
  780. const mask2 = collisionMatrix[group2.toString()];
  781. console.log(`组${group1}的碰撞掩码: ${mask1} (二进制: ${mask1?.toString(2)})`);
  782. console.log(`组${group2}的碰撞掩码: ${mask2} (二进制: ${mask2?.toString(2)})`);
  783. // 检查group1是否能与group2碰撞
  784. const canCollide1to2 = mask1 && (mask1 & (1 << group2)) !== 0;
  785. // 检查group2是否能与group1碰撞
  786. const canCollide2to1 = mask2 && (mask2 & (1 << group1)) !== 0;
  787. console.log(`组${group1}->组${group2}: ${canCollide1to2}`);
  788. console.log(`组${group2}->组${group1}: ${canCollide2to1}`);
  789. return canCollide1to2 && canCollide2to1;
  790. }
  791. // 初始化方向
  792. initializeDirection() {
  793. // 随机初始方向
  794. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  795. this.direction.x = Math.cos(angle);
  796. this.direction.y = Math.sin(angle);
  797. this.direction.normalize();
  798. console.log('Ball initialized with direction:', this.direction);
  799. // 设置初始速度
  800. if (this.activeBall) {
  801. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  802. if (rigidBody) {
  803. rigidBody.linearVelocity = new Vec2(
  804. this.direction.x * this.speed,
  805. this.direction.y * this.speed
  806. );
  807. console.log('Ball initial velocity set:', rigidBody.linearVelocity);
  808. } else {
  809. console.error('无法找到小球的RigidBody2D组件');
  810. }
  811. }
  812. }
  813. // 初始化球的参数 - 公开方法,供GameManager调用
  814. public initialize() {
  815. console.log('🎮 === BallController 初始化 ===');
  816. this.calculateGameBounds();
  817. this.createBall();
  818. // 检查方块碰撞体(延迟执行,确保方块已放置)
  819. this.scheduleOnce(() => {
  820. this.checkBlockColliders();
  821. }, 0.5);
  822. console.log('🎮 === BallController 初始化完成 ===');
  823. }
  824. // 启动小球 - 公开方法,在确定按钮点击后调用
  825. public startBall() {
  826. console.log('🚀 === 启动小球系统 ===');
  827. // 如果还没有初始化,先初始化
  828. if (!this.initialized) {
  829. this.initialize();
  830. }
  831. // 确保小球存在且有效
  832. if (!this.activeBall || !this.activeBall.isValid) {
  833. console.log('⚠️ 小球不存在,重新创建...');
  834. this.createBall();
  835. }
  836. // 重新定位小球,避免与方块重叠
  837. console.log('📍 重新定位小球位置...');
  838. this.positionBallRandomly();
  839. // 确保物理组件设置正确
  840. this.setupCollider();
  841. // 初始化运动方向并开始运动
  842. this.initializeDirection();
  843. // 设置运动状态
  844. this.ballStarted = true;
  845. console.log('🚀 === 小球系统启动完成,开始运动 ===');
  846. }
  847. // 输出碰撞矩阵调试信息
  848. private logCollisionMatrix() {
  849. // 根据项目配置检查碰撞矩阵
  850. // "collisionMatrix": { "0": 3, "1": 39, "2": 6, "3": 16, "4": 40, "5": 18 }
  851. const collisionMatrix: { [key: string]: number } = {
  852. "0": 3,
  853. "1": 39,
  854. "2": 6,
  855. "3": 16,
  856. "4": 40,
  857. "5": 18
  858. };
  859. console.log('🔍 === 碰撞矩阵配置 ===');
  860. for (const group in collisionMatrix) {
  861. const mask = collisionMatrix[group];
  862. console.log(`组 ${group}: 掩码 ${mask} (二进制: ${mask?.toString(2)})`);
  863. }
  864. // 测试Ball组(1)和Block组(2)是否能碰撞
  865. const ballMask = collisionMatrix["1"]; // 39
  866. const blockMask = collisionMatrix["2"]; // 6
  867. const ballCanCollideWithBlock = (ballMask & (1 << 2)) !== 0; // 检查Ball能否与组2碰撞
  868. const blockCanCollideWithBall = (blockMask & (1 << 1)) !== 0; // 检查Block能否与组1碰撞
  869. console.log('🎯 碰撞测试结果:');
  870. console.log(`Ball组(1) -> Block组(2): ${ballCanCollideWithBlock}`);
  871. console.log(`Block组(2) -> Ball组(1): ${blockCanCollideWithBall}`);
  872. console.log(`双向碰撞可用: ${ballCanCollideWithBlock && blockCanCollideWithBall}`);
  873. console.log('🔍 === 碰撞矩阵分析完成 ===');
  874. }
  875. /**
  876. * 从给定世界坐标发射子弹
  877. */
  878. private fireBulletAt(blockNode: Node, fireWorldPos: Vec3) {
  879. console.log('🔫 === 方块武器发射子弹流程 ===');
  880. console.log('激活的方块:', blockNode.name);
  881. console.log('方块路径:', this.getNodePath(blockNode));
  882. // 检查子弹预制体是否存在
  883. if (!this.bulletPrefab) {
  884. console.error('❌ 子弹预制体未设置');
  885. return;
  886. }
  887. // 直接使用碰撞世界坐标作为发射点
  888. this.createAndFireBullet(fireWorldPos);
  889. console.log('🔫 === 方块武器发射子弹流程结束 ===');
  890. }
  891. }