BallController.ts 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. import { _decorator, Component, Node, Vec2, Vec3, UITransform, Collider2D, Contact2DType, IPhysics2DContact, RigidBody2D, Prefab, instantiate, find, CircleCollider2D } from 'cc';
  2. import { PhysicsManager } from '../Core/PhysicsManager';
  3. import { WeaponBullet, BulletInitData, WeaponConfig } from './WeaponBullet';
  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. const physics = PhysicsManager.getInstance()?.getSystem();
  384. if (physics) {
  385. // 先移除旧监听,避免重复注册
  386. physics.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  387. physics.off(Contact2DType.END_CONTACT, this.onEndContact, this);
  388. physics.off(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
  389. physics.off(Contact2DType.POST_SOLVE, this.onPostSolve, this);
  390. physics.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  391. physics.on(Contact2DType.END_CONTACT, this.onEndContact, this);
  392. physics.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
  393. physics.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
  394. console.log('✅ 已注册全局碰撞监听器');
  395. }
  396. console.log('✅ 小球碰撞组件设置完成');
  397. console.log('⚙️ === 碰撞组件设置完成 ===');
  398. }
  399. // 碰撞回调 - 简化版本用于测试
  400. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  401. // Debug logs removed
  402. // 判断哪个是小球,哪个是方块
  403. let ballNode: Node = null;
  404. let blockNode: Node = null;
  405. // 检查self是否为小球(组1)
  406. if (selfCollider.group === 1) {
  407. ballNode = selfCollider.node;
  408. blockNode = otherCollider.node;
  409. }
  410. // 检查other是否为小球(组1)
  411. else if (otherCollider.group === 1) {
  412. ballNode = otherCollider.node;
  413. blockNode = selfCollider.node;
  414. }
  415. // 如果没有找到小球,跳过处理
  416. if (!ballNode || !blockNode) {
  417. // Debug log removed
  418. return;
  419. }
  420. // Debug log removed
  421. // 检查碰撞对象是否为方块
  422. const nodeName = blockNode.name;
  423. const nodePath = this.getNodePath(blockNode);
  424. // 检查是否有Weapon子节点(判断是否为方块)
  425. const hasWeaponChild = blockNode.getChildByName('Weapon') !== null;
  426. const isBlock =
  427. nodeName.includes('Block') ||
  428. nodePath.includes('Block') ||
  429. hasWeaponChild;
  430. // Debug log removed
  431. if (isBlock) {
  432. // trigger bullet without verbose logging
  433. // 计算碰撞世界坐标,默认用接触点
  434. let contactPos: Vec3 = null;
  435. if (contact && (contact as any).getWorldManifold) {
  436. const wm = (contact as any).getWorldManifold();
  437. if (wm && wm.points && wm.points.length > 0) {
  438. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  439. }
  440. }
  441. if (!contactPos) {
  442. contactPos = blockNode.worldPosition.clone();
  443. }
  444. const now = performance.now();
  445. const lastTime = this.blockFireCooldown.get(blockNode.uuid) || 0;
  446. if (now - lastTime > this.FIRE_COOLDOWN * 1000) {
  447. this.blockFireCooldown.set(blockNode.uuid, now);
  448. this.fireBulletAt(blockNode, contactPos);
  449. }
  450. }
  451. }
  452. // 碰撞结束事件 - 简化版本
  453. onEndContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  454. // Debug log removed
  455. }
  456. // 碰撞预处理事件 - 简化版本
  457. onPreSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  458. // console.log('⚙️ 碰撞预处理:', otherCollider.node.name);
  459. }
  460. // 碰撞后处理事件 - 简化版本
  461. onPostSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  462. // console.log('✅ 碰撞后处理:', otherCollider.node.name);
  463. }
  464. // 计算反射向量
  465. calculateReflection(direction: Vec2, normal: Vec2): Vec2 {
  466. // 使用反射公式: R = V - 2(V·N)N
  467. const dot = direction.x * normal.x + direction.y * normal.y;
  468. const reflection = new Vec2(
  469. direction.x - 2 * dot * normal.x,
  470. direction.y - 2 * dot * normal.y
  471. );
  472. reflection.normalize();
  473. // 添加一些随机性,避免重复的反弹路径
  474. const randomAngle = (Math.random() - 0.5) * this.maxReflectionRandomness; // 随机角度
  475. const cos = Math.cos(randomAngle);
  476. const sin = Math.sin(randomAngle);
  477. // 应用随机旋转
  478. const randomizedReflection = new Vec2(
  479. reflection.x * cos - reflection.y * sin,
  480. reflection.x * sin + reflection.y * cos
  481. );
  482. // 确保反射方向不会太接近水平或垂直方向
  483. // 这有助于避免球在水平或垂直方向上来回反弹
  484. const minAngleFromAxis = 0.1; // 约5.7度
  485. // 检查是否接近水平方向
  486. if (Math.abs(randomizedReflection.y) < minAngleFromAxis) {
  487. // 调整y分量,使其远离水平方向
  488. const sign = randomizedReflection.y >= 0 ? 1 : -1;
  489. randomizedReflection.y = sign * (minAngleFromAxis + Math.random() * 0.1);
  490. // 重新归一化
  491. randomizedReflection.normalize();
  492. }
  493. // 检查是否接近垂直方向
  494. if (Math.abs(randomizedReflection.x) < minAngleFromAxis) {
  495. // 调整x分量,使其远离垂直方向
  496. const sign = randomizedReflection.x >= 0 ? 1 : -1;
  497. randomizedReflection.x = sign * (minAngleFromAxis + Math.random() * 0.1);
  498. // 重新归一化
  499. randomizedReflection.normalize();
  500. }
  501. randomizedReflection.normalize();
  502. // Debug log removed
  503. return randomizedReflection;
  504. }
  505. /**
  506. * 从方块武器发射子弹攻击敌人 - 重构版本
  507. * 现在直接创建子弹实例并使用BulletController的实例方法
  508. * @param blockNode 激活的方块节点
  509. */
  510. fireBullet(blockNode: Node) {
  511. // Debug logs removed
  512. console.log('🔫 === 方块武器发射子弹流程 ===');
  513. console.log('激活的方块:', blockNode.name);
  514. console.log('方块路径:', this.getNodePath(blockNode));
  515. // 检查子弹预制体是否存在
  516. if (!this.bulletPrefab) {
  517. console.error('❌ 子弹预制体未设置');
  518. return;
  519. }
  520. // 查找方块中的Weapon节点
  521. console.log('🔍 开始查找方块中的Weapon节点...');
  522. const weaponNode = this.findWeaponNode(blockNode);
  523. if (!weaponNode) {
  524. console.error('❌ 在方块中找不到Weapon节点:', blockNode.name);
  525. const blockWorldPos = blockNode.worldPosition;
  526. const weaponConfig2: WeaponConfig | null = (blockNode as any)['weaponConfig'] || null;
  527. this.createAndFireBullet(blockWorldPos, weaponConfig2);
  528. console.log('🔫 === 方块武器发射子弹流程结束 ===');
  529. return;
  530. }
  531. // 获取武器的世界坐标作为发射位置
  532. let firePosition: Vec3;
  533. try {
  534. firePosition = weaponNode.worldPosition;
  535. } catch (error) {
  536. console.error('❌ 获取武器坐标失败:', error);
  537. // 备用方案:使用方块坐标
  538. firePosition = blockNode.worldPosition;
  539. }
  540. // 创建并发射子弹
  541. const weaponConfig: WeaponConfig | null = (blockNode as any)['weaponConfig'] || null;
  542. this.createAndFireBullet(firePosition, weaponConfig);
  543. console.log('🔫 === 方块武器发射子弹流程结束 ===');
  544. }
  545. /**
  546. * 创建并发射子弹 - 使用新的WeaponBullet系统
  547. * @param firePosition 发射位置(世界坐标)
  548. * @param weaponConfig 武器配置
  549. */
  550. private createAndFireBullet(firePosition: Vec3, weaponConfig: WeaponConfig | null) {
  551. console.log('🔫 === 开始创建子弹(新WeaponBullet系统)===');
  552. // 确保武器配置加载
  553. WeaponBullet.loadWeaponsData().then(() => {
  554. // 默认使用毛豆射手配置,后续可以根据方块类型动态选择
  555. const defaultWeaponId = 'pea_shooter';
  556. const finalConfig = weaponConfig || WeaponBullet.getWeaponConfig(defaultWeaponId);
  557. if (!finalConfig) {
  558. console.error('❌ 无法获取武器配置');
  559. return;
  560. }
  561. // 创建子弹初始化数据
  562. const initData: BulletInitData = {
  563. weaponId: finalConfig.id,
  564. firePosition: firePosition,
  565. autoTarget: true,
  566. weaponConfig: finalConfig
  567. };
  568. // 验证初始化数据
  569. if (!WeaponBullet.validateInitData(initData)) {
  570. console.error('❌ 子弹初始化数据无效');
  571. return;
  572. }
  573. // 判断是否为多发子弹(散射/连发等)
  574. const countCfg = finalConfig.bulletConfig.count;
  575. const isMultiShot = countCfg && countCfg.type !== 'single' && countCfg.amount > 1;
  576. // 查找GameArea(子弹统一添加到此节点)
  577. const gameArea = find('Canvas/GameLevelUI/GameArea');
  578. if (!gameArea) {
  579. console.error('❌ 找不到GameArea节点');
  580. return;
  581. }
  582. if (isMultiShot) {
  583. // 使用批量创建逻辑
  584. const bullets = WeaponBullet.createBullets(initData, this.bulletPrefab as any);
  585. bullets.forEach(b => {
  586. gameArea.addChild(b);
  587. });
  588. console.log(`✅ 已创建多发子弹 (${bullets.length} 发)`);
  589. } else {
  590. // 单发逻辑(沿用原流程)
  591. const bullet = instantiate(this.bulletPrefab);
  592. if (!bullet) {
  593. console.error('❌ 子弹实例创建失败');
  594. return;
  595. }
  596. gameArea.addChild(bullet);
  597. let weaponBullet = bullet.getComponent(WeaponBullet);
  598. if (!weaponBullet) {
  599. weaponBullet = bullet.addComponent(WeaponBullet);
  600. }
  601. weaponBullet.init(initData);
  602. console.log('✅ 新子弹系统创建完成 (单发)');
  603. }
  604. console.log('🔫 === 子弹创建完成 ===');
  605. }).catch(error => {
  606. console.error('❌ 武器配置加载失败:', error);
  607. });
  608. }
  609. // 递归查找Weapon节点
  610. private findWeaponNode(node: Node): Node | null {
  611. // logs removed
  612. console.log(`🔍 在节点 ${node.name} 中查找Weapon...`);
  613. // 先检查当前节点是否有Weapon子节点
  614. const weaponNode = node.getChildByName('Weapon');
  615. if (weaponNode) {
  616. console.log(`✅ 在 ${node.name} 中找到Weapon节点`);
  617. return weaponNode;
  618. }
  619. // 如果没有,递归检查所有子节点
  620. for (let i = 0; i < node.children.length; i++) {
  621. const child = node.children[i];
  622. console.log(` 🔍 检查子节点: ${child.name}`);
  623. const foundWeapon = this.findWeaponNode(child);
  624. if (foundWeapon) {
  625. console.log(`✅ 在 ${child.name} 的子节点中找到Weapon`);
  626. return foundWeapon;
  627. }
  628. }
  629. // 如果都没找到,返回null
  630. console.log(`❌ 在 ${node.name} 及其子节点中未找到Weapon`);
  631. return null;
  632. }
  633. // 辅助方法:打印节点结构
  634. private logNodeStructure(node: Node, depth: number) {
  635. const indent = ' '.repeat(depth);
  636. console.log(`${indent}${node.name}`);
  637. for (let i = 0; i < node.children.length; i++) {
  638. this.logNodeStructure(node.children[i], depth + 1);
  639. }
  640. }
  641. // 获取节点的完整路径
  642. private getNodePath(node: Node): string {
  643. let path = node.name;
  644. let current = node;
  645. while (current.parent) {
  646. current = current.parent;
  647. path = current.name + '/' + path;
  648. }
  649. return path;
  650. }
  651. update(dt: number) {
  652. // 只有当小球已启动时才执行运动逻辑
  653. if (!this.ballStarted || !this.initialized || !this.activeBall || !this.activeBall.isValid) {
  654. return;
  655. }
  656. // 使用刚体组件控制小球移动,而不是直接设置位置
  657. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  658. if (rigidBody) {
  659. // 获取当前速度并确保方向向量与实际速度方向一致
  660. const currentVelocity = rigidBody.linearVelocity;
  661. const speed = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
  662. // 确保方向向量与实际速度方向一致
  663. if (speed > 1.0) {
  664. this.direction.x = currentVelocity.x / speed;
  665. this.direction.y = currentVelocity.y / speed;
  666. }
  667. // 如果速度过低,重新设置速度以维持恒定运动
  668. if (speed < this.speed * 0.9) {
  669. rigidBody.linearVelocity = new Vec2(
  670. this.direction.x * this.speed,
  671. this.direction.y * this.speed
  672. );
  673. }
  674. // 定期检查小球是否接近方块但没有触发碰撞(调试用)
  675. this.debugCheckNearBlocks();
  676. }
  677. }
  678. // 调试方法:检查小球是否接近方块但没有触发物理碰撞
  679. private debugCheckCounter = 0;
  680. private debugCheckNearBlocks() {
  681. this.debugCheckCounter++;
  682. // 每60帧(约1秒)检查一次
  683. if (this.debugCheckCounter % 60 !== 0) return;
  684. const ballPos = this.activeBall.worldPosition;
  685. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) return;
  686. let nearestDistance = Infinity;
  687. let nearestBlock = null;
  688. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  689. const block = this.placedBlocksContainer.children[i];
  690. if (block.name.includes('Block') || block.getChildByName('B1')) {
  691. const blockPos = block.worldPosition;
  692. const distance = Math.sqrt(
  693. Math.pow(ballPos.x - blockPos.x, 2) +
  694. Math.pow(ballPos.y - blockPos.y, 2)
  695. );
  696. if (distance < nearestDistance) {
  697. nearestDistance = distance;
  698. nearestBlock = block;
  699. }
  700. }
  701. }
  702. if (nearestBlock && nearestDistance < 100) {
  703. console.log(`⚠️ 小球接近方块但无物理碰撞: 距离=${nearestDistance.toFixed(1)}, 方块=${nearestBlock.name}`);
  704. console.log('小球位置:', ballPos);
  705. console.log('方块位置:', nearestBlock.worldPosition);
  706. // 检查小球的碰撞体状态
  707. console.log('=== 小球碰撞体详细检查 ===');
  708. const ballCollider = this.activeBall.getComponent(Collider2D);
  709. console.log('小球有碰撞体:', !!ballCollider);
  710. if (ballCollider) {
  711. console.log('小球碰撞体类型:', ballCollider.constructor.name);
  712. console.log('小球碰撞组:', ballCollider.group);
  713. console.log('小球碰撞标签:', ballCollider.tag);
  714. console.log('小球是否为传感器:', ballCollider.sensor);
  715. console.log('小球碰撞体是否启用:', ballCollider.enabled);
  716. if (ballCollider instanceof CircleCollider2D) {
  717. console.log('小球碰撞半径:', ballCollider.radius);
  718. }
  719. }
  720. // 检查小球的刚体状态
  721. const ballRigidBody = this.activeBall.getComponent(RigidBody2D);
  722. console.log('小球有刚体:', !!ballRigidBody);
  723. if (ballRigidBody) {
  724. console.log('小球刚体类型:', ballRigidBody.type);
  725. console.log('小球刚体启用碰撞监听:', ballRigidBody.enabledContactListener);
  726. console.log('小球刚体是否启用:', ballRigidBody.enabled);
  727. }
  728. // 检查最近的方块碰撞体
  729. console.log('=== 方块碰撞体详细检查 ===');
  730. const blockCollider = nearestBlock.getComponent(Collider2D);
  731. console.log('方块有碰撞体:', !!blockCollider);
  732. if (blockCollider) {
  733. console.log('方块碰撞体类型:', blockCollider.constructor.name);
  734. console.log('方块碰撞组:', blockCollider.group);
  735. console.log('方块碰撞标签:', blockCollider.tag);
  736. console.log('方块是否为传感器:', blockCollider.sensor);
  737. console.log('方块碰撞体是否启用:', blockCollider.enabled);
  738. }
  739. // (已移除碰撞矩阵与物理引擎状态的冗余调试输出)
  740. }
  741. }
  742. // 检查碰撞矩阵
  743. private checkCollisionMatrix(group1: number, group2: number): boolean {
  744. // 根据项目配置检查碰撞矩阵
  745. // "collisionMatrix": { "0": 3, "1": 39, "2": 6, "3": 16, "4": 40, "5": 18 }
  746. const collisionMatrix: { [key: string]: number } = {
  747. "0": 3,
  748. "1": 39,
  749. "2": 6,
  750. "3": 16,
  751. "4": 40,
  752. "5": 18
  753. };
  754. const mask1 = collisionMatrix[group1.toString()];
  755. const mask2 = collisionMatrix[group2.toString()];
  756. // (调试输出移除)
  757. // 检查group1是否能与group2碰撞
  758. const canCollide1to2 = mask1 && (mask1 & (1 << group2)) !== 0;
  759. // 检查group2是否能与group1碰撞
  760. const canCollide2to1 = mask2 && (mask2 & (1 << group1)) !== 0;
  761. // (调试输出移除)
  762. return canCollide1to2 && canCollide2to1;
  763. }
  764. // 初始化方向
  765. initializeDirection() {
  766. // 随机初始方向
  767. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  768. this.direction.x = Math.cos(angle);
  769. this.direction.y = Math.sin(angle);
  770. this.direction.normalize();
  771. console.log('Ball initialized with direction:', this.direction);
  772. // 设置初始速度
  773. if (this.activeBall) {
  774. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  775. if (rigidBody) {
  776. rigidBody.linearVelocity = new Vec2(
  777. this.direction.x * this.speed,
  778. this.direction.y * this.speed
  779. );
  780. console.log('Ball initial velocity set:', rigidBody.linearVelocity);
  781. } else {
  782. console.error('无法找到小球的RigidBody2D组件');
  783. }
  784. }
  785. }
  786. // 初始化球的参数 - 公开方法,供GameManager调用
  787. public initialize() {
  788. console.log('🎮 === BallController 初始化 ===');
  789. this.calculateGameBounds();
  790. this.createBall();
  791. // 检查方块碰撞体(延迟执行,确保方块已放置)
  792. this.scheduleOnce(() => {
  793. this.checkBlockColliders();
  794. }, 0.5);
  795. console.log('🎮 === BallController 初始化完成 ===');
  796. }
  797. // 启动小球 - 公开方法,在确定按钮点击后调用
  798. public startBall() {
  799. console.log('🚀 === 启动小球系统 ===');
  800. // 如果还没有初始化,先初始化
  801. if (!this.initialized) {
  802. this.initialize();
  803. }
  804. // 确保小球存在且有效
  805. if (!this.activeBall || !this.activeBall.isValid) {
  806. console.log('⚠️ 小球不存在,重新创建...');
  807. this.createBall();
  808. }
  809. // 重新定位小球,避免与方块重叠
  810. console.log('📍 重新定位小球位置...');
  811. this.positionBallRandomly();
  812. // 确保物理组件设置正确
  813. this.setupCollider();
  814. // 初始化运动方向并开始运动
  815. this.initializeDirection();
  816. // 设置运动状态
  817. this.ballStarted = true;
  818. console.log('🚀 === 小球系统启动完成,开始运动 ===');
  819. }
  820. // 输出碰撞矩阵调试信息
  821. private logCollisionMatrix() {
  822. // 根据项目配置检查碰撞矩阵
  823. // "collisionMatrix": { "0": 3, "1": 39, "2": 6, "3": 16, "4": 40, "5": 18 }
  824. const collisionMatrix: { [key: string]: number } = {
  825. "0": 3,
  826. "1": 39,
  827. "2": 6,
  828. "3": 16,
  829. "4": 40,
  830. "5": 18
  831. };
  832. // (调试输出移除)
  833. // 测试Ball组(1)和Block组(2)是否能碰撞
  834. const ballMask = collisionMatrix["1"]; // 39
  835. const blockMask = collisionMatrix["2"]; // 6
  836. const ballCanCollideWithBlock = (ballMask & (1 << 2)) !== 0; // 检查Ball能否与组2碰撞
  837. const blockCanCollideWithBall = (blockMask & (1 << 1)) !== 0; // 检查Block能否与组1碰撞
  838. // (调试输出移除)
  839. // (调试输出移除)
  840. }
  841. /**
  842. * 从给定世界坐标发射子弹
  843. */
  844. private fireBulletAt(blockNode: Node, fireWorldPos: Vec3) {
  845. console.log('🔫 === 方块武器发射子弹流程 ===');
  846. console.log('激活的方块:', blockNode.name);
  847. console.log('方块路径:', this.getNodePath(blockNode));
  848. // 检查子弹预制体是否存在
  849. if (!this.bulletPrefab) {
  850. console.error('❌ 子弹预制体未设置');
  851. return;
  852. }
  853. // 直接使用碰撞世界坐标作为发射点
  854. const weaponConfig: WeaponConfig | null = (blockNode as any)['weaponConfig'] || null;
  855. this.createAndFireBullet(fireWorldPos, weaponConfig);
  856. console.log('🔫 === 方块武器发射子弹流程结束 ===');
  857. }
  858. }