BallController.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  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. // 找不到PlacedBlocks节点,某些功能可能无法正常工作
  57. }
  58. }
  59. // 只进行初始设置,不创建小球
  60. this.calculateGameBounds();
  61. // 延迟执行一些检查方法,但不创建小球
  62. this.scheduleOnce(() => {
  63. this.logCollisionMatrix();
  64. }, 1.0);
  65. }
  66. // 计算游戏边界(使用GameArea节点)
  67. calculateGameBounds() {
  68. // 获取GameArea节点
  69. const gameArea = find('Canvas/GameLevelUI/GameArea');
  70. if (!gameArea) {
  71. return;
  72. }
  73. const gameAreaUI = gameArea.getComponent(UITransform);
  74. if (!gameAreaUI) {
  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. }
  88. // 创建小球
  89. createBall() {
  90. if (!this.ballPrefab) {
  91. return;
  92. }
  93. // 如果已经有活动的球,先销毁它
  94. if (this.activeBall && this.activeBall.isValid) {
  95. this.activeBall.destroy();
  96. }
  97. // 实例化小球
  98. this.activeBall = instantiate(this.ballPrefab);
  99. // 将小球添加到GameArea中
  100. const gameArea = find('Canvas/GameLevelUI/GameArea');
  101. if (gameArea) {
  102. gameArea.addChild(this.activeBall);
  103. } else {
  104. this.node.addChild(this.activeBall);
  105. }
  106. // 随机位置小球
  107. this.positionBallRandomly();
  108. // 设置球的半径
  109. const transform = this.activeBall.getComponent(UITransform);
  110. if (transform) {
  111. this.radius = transform.width / 2;
  112. } else {
  113. this.radius = 25; // 默认半径
  114. }
  115. // 确保有碰撞组件
  116. this.setupCollider();
  117. // 注意:不在这里初始化方向,等待 startBall() 调用
  118. this.initialized = true;
  119. }
  120. // 检查所有已放置方块的碰撞体组件
  121. private checkBlockColliders() {
  122. if (!this.placedBlocksContainer) {
  123. return;
  124. }
  125. if (!this.placedBlocksContainer.isValid) {
  126. return;
  127. }
  128. const blocks = [];
  129. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  130. const block = this.placedBlocksContainer.children[i];
  131. if (block.name.includes('Block') || block.getChildByName('B1')) {
  132. blocks.push(block);
  133. }
  134. }
  135. let fixedCount = 0;
  136. for (let i = 0; i < blocks.length; i++) {
  137. const block = blocks[i];
  138. // 检查方块本身的碰撞体
  139. const blockCollider = block.getComponent(Collider2D);
  140. if (blockCollider) {
  141. // 🔧 自动修复碰撞组设置
  142. if (blockCollider.group !== 2) {
  143. blockCollider.group = 2; // 设置为Block组
  144. fixedCount++;
  145. }
  146. // 确保不是传感器
  147. if (blockCollider.sensor) {
  148. blockCollider.sensor = false;
  149. }
  150. }
  151. // 检查B1子节点的碰撞体
  152. const b1Node = block.getChildByName('B1');
  153. if (b1Node) {
  154. const b1Collider = b1Node.getComponent(Collider2D);
  155. if (b1Collider) {
  156. // 🔧 修复B1子节点的碰撞设置
  157. if (b1Collider.group !== 2) {
  158. b1Collider.group = 2; // 设置为Block组
  159. fixedCount++;
  160. }
  161. // 确保B1不是传感器(需要实际碰撞)
  162. if (b1Collider.sensor) {
  163. b1Collider.sensor = false;
  164. }
  165. }
  166. }
  167. // 检查Weapon子节点
  168. const weaponNode = this.findWeaponNode(block);
  169. if (weaponNode) {
  170. // 武器节点存在
  171. }
  172. }
  173. }
  174. // 随机位置小球
  175. positionBallRandomly() {
  176. if (!this.activeBall) return;
  177. const transform = this.activeBall.getComponent(UITransform);
  178. const ballRadius = transform ? transform.width / 2 : 25;
  179. // 计算可生成的范围(考虑小球半径,避免生成在边缘)
  180. const minX = this.gameBounds.left + ballRadius + 20; // 额外偏移,避免生成在边缘
  181. const maxX = this.gameBounds.right - ballRadius - 20;
  182. const minY = this.gameBounds.bottom + ballRadius + 20;
  183. const maxY = this.gameBounds.top - ballRadius - 20;
  184. // 获取GameArea节点
  185. const gameArea = find('Canvas/GameLevelUI/GameArea');
  186. if (!gameArea) {
  187. return;
  188. }
  189. // 查找PlacedBlocks节点,它包含所有放置的方块
  190. if (!this.placedBlocksContainer) {
  191. this.setRandomPositionDefault(minX, maxX, minY, maxY);
  192. return;
  193. }
  194. if (!this.placedBlocksContainer.isValid) {
  195. this.setRandomPositionDefault(minX, maxX, minY, maxY);
  196. return;
  197. }
  198. // 获取所有已放置的方块
  199. const placedBlocks = [];
  200. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  201. const block = this.placedBlocksContainer.children[i];
  202. // 检查是否是方块节点(通常以Block命名或有特定标识)
  203. if (block.name.includes('Block') || block.getChildByName('B1')) {
  204. placedBlocks.push(block);
  205. }
  206. }
  207. // 如果没有方块,使用默认随机位置
  208. if (placedBlocks.length === 0) {
  209. this.setRandomPositionDefault(minX, maxX, minY, maxY);
  210. return;
  211. }
  212. // 尝试找到一个不与任何方块重叠的位置
  213. let validPosition = false;
  214. let attempts = 0;
  215. const maxAttempts = 50; // 最大尝试次数
  216. let randomX, randomY;
  217. while (!validPosition && attempts < maxAttempts) {
  218. // 随机生成位置
  219. randomX = Math.random() * (maxX - minX) + minX;
  220. randomY = Math.random() * (maxY - minY) + minY;
  221. // 检查是否与任何方块重叠
  222. let overlapping = false;
  223. for (const block of placedBlocks) {
  224. // 获取方块的世界坐标
  225. const blockWorldPos = block.worldPosition;
  226. // 计算小球与方块的距离
  227. const distance = Math.sqrt(
  228. Math.pow(randomX - blockWorldPos.x, 2) +
  229. Math.pow(randomY - blockWorldPos.y, 2)
  230. );
  231. // 获取方块的尺寸
  232. const blockTransform = block.getComponent(UITransform);
  233. const blockSize = blockTransform ?
  234. Math.max(blockTransform.width, blockTransform.height) / 2 : 50;
  235. // 如果距离小于小球半径+方块尺寸的一半+安全距离,认为重叠
  236. const safeDistance = 20; // 额外安全距离
  237. if (distance < ballRadius + blockSize + safeDistance) {
  238. overlapping = true;
  239. break;
  240. }
  241. }
  242. // 如果没有重叠,找到了有效位置
  243. if (!overlapping) {
  244. validPosition = true;
  245. }
  246. attempts++;
  247. }
  248. // 如果找不到有效位置,使用默认位置(游戏区域底部中心)
  249. if (!validPosition) {
  250. randomX = (this.gameBounds.left + this.gameBounds.right) / 2;
  251. randomY = this.gameBounds.bottom + ballRadius + 50; // 底部上方50单位
  252. }
  253. // 将世界坐标转换为相对于GameArea的本地坐标
  254. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  255. this.activeBall.position = localPos;
  256. }
  257. // 设置默认随机位置
  258. setRandomPositionDefault(minX, maxX, minY, maxY) {
  259. // 随机生成位置
  260. const randomX = Math.random() * (maxX - minX) + minX;
  261. const randomY = Math.random() * (maxY - minY) + minY;
  262. // 将世界坐标转换为相对于GameArea的本地坐标
  263. const gameArea = find('Canvas/GameLevelUI/GameArea');
  264. if (gameArea) {
  265. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  266. this.activeBall.position = localPos;
  267. } else {
  268. // 直接设置位置(不太准确,但作为后备)
  269. this.activeBall.position = new Vec3(randomX - this.gameBounds.left, randomY - this.gameBounds.bottom, 0);
  270. }
  271. }
  272. // 设置碰撞组件
  273. setupCollider() {
  274. if (!this.activeBall) return;
  275. // 确保小球有刚体组件
  276. let rigidBody = this.activeBall.getComponent(RigidBody2D);
  277. if (!rigidBody) {
  278. rigidBody = this.activeBall.addComponent(RigidBody2D);
  279. rigidBody.type = 2; // Dynamic
  280. rigidBody.gravityScale = 0; // 不受重力影响
  281. rigidBody.enabledContactListener = true; // 启用碰撞监听
  282. rigidBody.fixedRotation = true; // 固定旋转
  283. rigidBody.allowSleep = false; // 不允许休眠
  284. rigidBody.linearDamping = 0; // 无线性阻尼,保持速度不衰减
  285. rigidBody.angularDamping = 0; // 无角阻尼
  286. } else {
  287. // 确保已有的刚体组件设置正确
  288. rigidBody.enabledContactListener = true;
  289. rigidBody.gravityScale = 0;
  290. rigidBody.linearDamping = 0; // 确保无线性阻尼,保持速度不衰减
  291. rigidBody.angularDamping = 0; // 确保无角阻尼
  292. rigidBody.allowSleep = false; // 不允许休眠
  293. }
  294. // 确保小球有碰撞组件
  295. let collider = this.activeBall.getComponent(CircleCollider2D);
  296. if (!collider) {
  297. collider = this.activeBall.addComponent(CircleCollider2D);
  298. collider.radius = this.radius || 25; // 使用已计算的半径或默认值
  299. collider.tag = 1; // 小球标签
  300. collider.group = 1; // 碰撞组1 - Ball组
  301. collider.sensor = false; // 非传感器(实际碰撞)
  302. collider.friction = 0; // 无摩擦
  303. collider.restitution = 1; // 完全弹性碰撞
  304. } else {
  305. // 确保已有的碰撞组件设置正确
  306. collider.sensor = false;
  307. collider.restitution = 1;
  308. collider.group = 1; // 确保是Ball组
  309. collider.tag = 1; // 确保标签正确
  310. }
  311. // === 使用全局回调监听器 ===
  312. const physics = PhysicsManager.getInstance()?.getSystem();
  313. if (physics) {
  314. // 先移除旧监听,避免重复注册
  315. physics.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  316. physics.off(Contact2DType.END_CONTACT, this.onEndContact, this);
  317. physics.off(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
  318. physics.off(Contact2DType.POST_SOLVE, this.onPostSolve, this);
  319. physics.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  320. physics.on(Contact2DType.END_CONTACT, this.onEndContact, this);
  321. physics.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
  322. physics.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
  323. }
  324. }
  325. // 碰撞回调 - 简化版本用于测试
  326. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  327. // Debug logs removed
  328. // 判断哪个是小球,哪个是方块
  329. let ballNode: Node = null;
  330. let blockNode: Node = null;
  331. // 检查self是否为小球(组1)
  332. if (selfCollider.group === 1) {
  333. ballNode = selfCollider.node;
  334. blockNode = otherCollider.node;
  335. }
  336. // 检查other是否为小球(组1)
  337. else if (otherCollider.group === 1) {
  338. ballNode = otherCollider.node;
  339. blockNode = selfCollider.node;
  340. }
  341. // 如果没有找到小球,跳过处理
  342. if (!ballNode || !blockNode) {
  343. // Debug log removed
  344. return;
  345. }
  346. // 检查碰撞对象是否为方块
  347. const nodeName = blockNode.name;
  348. const nodePath = this.getNodePath(blockNode);
  349. // 检查是否有Weapon子节点(判断是否为方块)
  350. const hasWeaponChild = blockNode.getChildByName('Weapon') !== null;
  351. const isBlock =
  352. nodeName.includes('Block') ||
  353. nodePath.includes('Block') ||
  354. hasWeaponChild;
  355. if (isBlock) {
  356. // trigger bullet without verbose logging
  357. // 计算碰撞世界坐标,默认用接触点
  358. let contactPos: Vec3 = null;
  359. if (contact && (contact as any).getWorldManifold) {
  360. const wm = (contact as any).getWorldManifold();
  361. if (wm && wm.points && wm.points.length > 0) {
  362. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  363. }
  364. }
  365. if (!contactPos) {
  366. contactPos = blockNode.worldPosition.clone();
  367. }
  368. const now = performance.now();
  369. const lastTime = this.blockFireCooldown.get(blockNode.uuid) || 0;
  370. if (now - lastTime > this.FIRE_COOLDOWN * 1000) {
  371. this.blockFireCooldown.set(blockNode.uuid, now);
  372. this.fireBulletAt(blockNode, contactPos);
  373. }
  374. }
  375. }
  376. // 碰撞结束事件 - 简化版本
  377. onEndContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  378. // Debug log removed
  379. }
  380. // 碰撞预处理事件 - 简化版本
  381. onPreSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  382. // console.log('⚙️ 碰撞预处理:', otherCollider.node.name);
  383. }
  384. // 碰撞后处理事件 - 简化版本
  385. onPostSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  386. // console.log('✅ 碰撞后处理:', otherCollider.node.name);
  387. }
  388. // 计算反射向量
  389. calculateReflection(direction: Vec2, normal: Vec2): Vec2 {
  390. // 使用反射公式: R = V - 2(V·N)N
  391. const dot = direction.x * normal.x + direction.y * normal.y;
  392. const reflection = new Vec2(
  393. direction.x - 2 * dot * normal.x,
  394. direction.y - 2 * dot * normal.y
  395. );
  396. reflection.normalize();
  397. // 添加一些随机性,避免重复的反弹路径
  398. const randomAngle = (Math.random() - 0.5) * this.maxReflectionRandomness; // 随机角度
  399. const cos = Math.cos(randomAngle);
  400. const sin = Math.sin(randomAngle);
  401. // 应用随机旋转
  402. const randomizedReflection = new Vec2(
  403. reflection.x * cos - reflection.y * sin,
  404. reflection.x * sin + reflection.y * cos
  405. );
  406. // 确保反射方向不会太接近水平或垂直方向
  407. // 这有助于避免球在水平或垂直方向上来回反弹
  408. const minAngleFromAxis = 0.1; // 约5.7度
  409. // 检查是否接近水平方向
  410. if (Math.abs(randomizedReflection.y) < minAngleFromAxis) {
  411. // 调整y分量,使其远离水平方向
  412. const sign = randomizedReflection.y >= 0 ? 1 : -1;
  413. randomizedReflection.y = sign * (minAngleFromAxis + Math.random() * 0.1);
  414. // 重新归一化
  415. randomizedReflection.normalize();
  416. }
  417. // 检查是否接近垂直方向
  418. if (Math.abs(randomizedReflection.x) < minAngleFromAxis) {
  419. // 调整x分量,使其远离垂直方向
  420. const sign = randomizedReflection.x >= 0 ? 1 : -1;
  421. randomizedReflection.x = sign * (minAngleFromAxis + Math.random() * 0.1);
  422. // 重新归一化
  423. randomizedReflection.normalize();
  424. }
  425. randomizedReflection.normalize();
  426. // Debug log removed
  427. return randomizedReflection;
  428. }
  429. /**
  430. * 从方块武器发射子弹攻击敌人 - 重构版本
  431. * 现在直接创建子弹实例并使用BulletController的实例方法
  432. * @param blockNode 激活的方块节点
  433. */
  434. fireBullet(blockNode: Node) {
  435. // Debug logs removed
  436. // 检查子弹预制体是否存在
  437. if (!this.bulletPrefab) {
  438. return;
  439. }
  440. // 查找方块中的Weapon节点
  441. const weaponNode = this.findWeaponNode(blockNode);
  442. if (!weaponNode) {
  443. const blockWorldPos = blockNode.worldPosition;
  444. const weaponConfig2: WeaponConfig | null = (blockNode as any)['weaponConfig'] || null;
  445. this.createAndFireBullet(blockWorldPos, weaponConfig2);
  446. return;
  447. }
  448. // 获取武器的世界坐标作为发射位置
  449. let firePosition: Vec3;
  450. try {
  451. firePosition = weaponNode.worldPosition;
  452. } catch (error) {
  453. // 备用方案:使用方块坐标
  454. firePosition = blockNode.worldPosition;
  455. }
  456. // 创建并发射子弹
  457. const weaponConfig: WeaponConfig | null = (blockNode as any)['weaponConfig'] || null;
  458. this.createAndFireBullet(firePosition, weaponConfig);
  459. }
  460. /**
  461. * 创建并发射子弹 - 使用新的WeaponBullet系统
  462. * @param firePosition 发射位置(世界坐标)
  463. * @param weaponConfig 武器配置
  464. */
  465. private createAndFireBullet(firePosition: Vec3, weaponConfig: WeaponConfig | null) {
  466. // 确保武器配置加载
  467. WeaponBullet.loadWeaponsData().then(() => {
  468. // 默认使用毛豆射手配置,后续可以根据方块类型动态选择
  469. const defaultWeaponId = 'pea_shooter';
  470. const finalConfig = weaponConfig || WeaponBullet.getWeaponConfig(defaultWeaponId);
  471. if (!finalConfig) {
  472. return;
  473. }
  474. // 创建子弹初始化数据
  475. const initData: BulletInitData = {
  476. weaponId: finalConfig.id,
  477. firePosition: firePosition,
  478. autoTarget: true,
  479. weaponConfig: finalConfig
  480. };
  481. // 验证初始化数据
  482. if (!WeaponBullet.validateInitData(initData)) {
  483. return;
  484. }
  485. // 判断是否为多发子弹(散射/连发等)
  486. const countCfg = finalConfig.bulletConfig.count;
  487. const isMultiShot = countCfg && countCfg.type !== 'single' && countCfg.amount > 1;
  488. // 查找GameArea(子弹统一添加到此节点)
  489. const gameArea = find('Canvas/GameLevelUI/GameArea');
  490. if (!gameArea) {
  491. return;
  492. }
  493. if (isMultiShot) {
  494. // 使用批量创建逻辑
  495. const bullets = WeaponBullet.createBullets(initData, this.bulletPrefab as any);
  496. bullets.forEach(b => {
  497. gameArea.addChild(b);
  498. });
  499. } else {
  500. // 单发逻辑(沿用原流程)
  501. const bullet = instantiate(this.bulletPrefab);
  502. if (!bullet) {
  503. return;
  504. }
  505. gameArea.addChild(bullet);
  506. let weaponBullet = bullet.getComponent(WeaponBullet);
  507. if (!weaponBullet) {
  508. weaponBullet = bullet.addComponent(WeaponBullet);
  509. }
  510. weaponBullet.init(initData);
  511. }
  512. }).catch(error => {
  513. // 武器配置加载失败
  514. });
  515. }
  516. // 递归查找Weapon节点
  517. private findWeaponNode(node: Node): Node | null {
  518. // logs removed
  519. // 先检查当前节点是否有Weapon子节点
  520. const weaponNode = node.getChildByName('Weapon');
  521. if (weaponNode) {
  522. return weaponNode;
  523. }
  524. // 如果没有,递归检查所有子节点
  525. for (let i = 0; i < node.children.length; i++) {
  526. const child = node.children[i];
  527. const foundWeapon = this.findWeaponNode(child);
  528. if (foundWeapon) {
  529. return foundWeapon;
  530. }
  531. }
  532. // 如果都没找到,返回null
  533. return null;
  534. }
  535. // 辅助方法:打印节点结构
  536. private logNodeStructure(node: Node, depth: number) {
  537. const indent = ' '.repeat(depth);
  538. for (let i = 0; i < node.children.length; i++) {
  539. this.logNodeStructure(node.children[i], depth + 1);
  540. }
  541. }
  542. // 获取节点的完整路径
  543. private getNodePath(node: Node): string {
  544. let path = node.name;
  545. let current = node;
  546. while (current.parent) {
  547. current = current.parent;
  548. path = current.name + '/' + path;
  549. }
  550. return path;
  551. }
  552. update(dt: number) {
  553. // 只有当小球已启动时才执行运动逻辑
  554. if (!this.ballStarted || !this.initialized || !this.activeBall || !this.activeBall.isValid) {
  555. return;
  556. }
  557. // 使用刚体组件控制小球移动,而不是直接设置位置
  558. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  559. if (rigidBody) {
  560. // 获取当前速度并确保方向向量与实际速度方向一致
  561. const currentVelocity = rigidBody.linearVelocity;
  562. const speed = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
  563. // 确保方向向量与实际速度方向一致
  564. if (speed > 1.0) {
  565. this.direction.x = currentVelocity.x / speed;
  566. this.direction.y = currentVelocity.y / speed;
  567. }
  568. // 如果速度过低,重新设置速度以维持恒定运动
  569. if (speed < this.speed * 0.9) {
  570. rigidBody.linearVelocity = new Vec2(
  571. this.direction.x * this.speed,
  572. this.direction.y * this.speed
  573. );
  574. }
  575. // 定期检查小球是否接近方块但没有触发碰撞(调试用)
  576. this.debugCheckNearBlocks();
  577. }
  578. }
  579. // 调试方法:检查小球是否接近方块但没有触发物理碰撞
  580. private debugCheckCounter = 0;
  581. private debugCheckNearBlocks() {
  582. this.debugCheckCounter++;
  583. // 每60帧(约1秒)检查一次
  584. if (this.debugCheckCounter % 60 !== 0) return;
  585. const ballPos = this.activeBall.worldPosition;
  586. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) return;
  587. let nearestDistance = Infinity;
  588. let nearestBlock = null;
  589. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  590. const block = this.placedBlocksContainer.children[i];
  591. if (block.name.includes('Block') || block.getChildByName('B1')) {
  592. const blockPos = block.worldPosition;
  593. const distance = Math.sqrt(
  594. Math.pow(ballPos.x - blockPos.x, 2) +
  595. Math.pow(ballPos.y - blockPos.y, 2)
  596. );
  597. if (distance < nearestDistance) {
  598. nearestDistance = distance;
  599. nearestBlock = block;
  600. }
  601. }
  602. }
  603. if (nearestBlock && nearestDistance < 100) {
  604. // 检查小球的碰撞体状态
  605. const ballCollider = this.activeBall.getComponent(Collider2D);
  606. if (ballCollider) {
  607. if (ballCollider instanceof CircleCollider2D) {
  608. // 小球碰撞半径检查
  609. }
  610. }
  611. // 检查小球的刚体状态
  612. const ballRigidBody = this.activeBall.getComponent(RigidBody2D);
  613. if (ballRigidBody) {
  614. // 刚体状态检查
  615. }
  616. // 检查最近的方块碰撞体
  617. const blockCollider = nearestBlock.getComponent(Collider2D);
  618. if (blockCollider) {
  619. // 方块碰撞体检查
  620. }
  621. }
  622. }
  623. // 检查碰撞矩阵
  624. private checkCollisionMatrix(group1: number, group2: number): boolean {
  625. // 根据项目配置检查碰撞矩阵
  626. // "collisionMatrix": { "0": 3, "1": 39, "2": 6, "3": 16, "4": 40, "5": 18 }
  627. const collisionMatrix: { [key: string]: number } = {
  628. "0": 3,
  629. "1": 39,
  630. "2": 6,
  631. "3": 16,
  632. "4": 40,
  633. "5": 18
  634. };
  635. const mask1 = collisionMatrix[group1.toString()];
  636. const mask2 = collisionMatrix[group2.toString()];
  637. // 检查group1是否能与group2碰撞
  638. const canCollide1to2 = mask1 && (mask1 & (1 << group2)) !== 0;
  639. // 检查group2是否能与group1碰撞
  640. const canCollide2to1 = mask2 && (mask2 & (1 << group1)) !== 0;
  641. return canCollide1to2 && canCollide2to1;
  642. }
  643. // 初始化方向
  644. initializeDirection() {
  645. // 随机初始方向
  646. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  647. this.direction.x = Math.cos(angle);
  648. this.direction.y = Math.sin(angle);
  649. this.direction.normalize();
  650. // 设置初始速度
  651. if (this.activeBall) {
  652. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  653. if (rigidBody) {
  654. rigidBody.linearVelocity = new Vec2(
  655. this.direction.x * this.speed,
  656. this.direction.y * this.speed
  657. );
  658. }
  659. }
  660. }
  661. // 初始化球的参数 - 公开方法,供GameManager调用
  662. public initialize() {
  663. this.calculateGameBounds();
  664. this.createBall();
  665. // 检查方块碰撞体(延迟执行,确保方块已放置)
  666. this.scheduleOnce(() => {
  667. this.checkBlockColliders();
  668. }, 0.5);
  669. }
  670. // 启动小球 - 公开方法,在确定按钮点击后调用
  671. public startBall() {
  672. // 如果还没有初始化,先初始化
  673. if (!this.initialized) {
  674. this.initialize();
  675. }
  676. // 确保小球存在且有效
  677. if (!this.activeBall || !this.activeBall.isValid) {
  678. this.createBall();
  679. }
  680. // 重新定位小球,避免与方块重叠
  681. this.positionBallRandomly();
  682. // 确保物理组件设置正确
  683. this.setupCollider();
  684. // 初始化运动方向并开始运动
  685. this.initializeDirection();
  686. // 设置运动状态
  687. this.ballStarted = true;
  688. }
  689. // 输出碰撞矩阵调试信息
  690. private logCollisionMatrix() {
  691. // 根据项目配置检查碰撞矩阵
  692. // "collisionMatrix": { "0": 3, "1": 39, "2": 6, "3": 16, "4": 40, "5": 18 }
  693. const collisionMatrix: { [key: string]: number } = {
  694. "0": 3,
  695. "1": 39,
  696. "2": 6,
  697. "3": 16,
  698. "4": 40,
  699. "5": 18
  700. };
  701. // 测试Ball组(1)和Block组(2)是否能碰撞
  702. const ballMask = collisionMatrix["1"]; // 39
  703. const blockMask = collisionMatrix["2"]; // 6
  704. const ballCanCollideWithBlock = (ballMask & (1 << 2)) !== 0; // 检查Ball能否与组2碰撞
  705. const blockCanCollideWithBall = (blockMask & (1 << 1)) !== 0; // 检查Block能否与组1碰撞
  706. }
  707. /**
  708. * 从给定世界坐标发射子弹
  709. */
  710. private fireBulletAt(blockNode: Node, fireWorldPos: Vec3) {
  711. // 检查子弹预制体是否存在
  712. if (!this.bulletPrefab) {
  713. return;
  714. }
  715. // 直接使用碰撞世界坐标作为发射点
  716. const weaponConfig: WeaponConfig | null = (blockNode as any)['weaponConfig'] || null;
  717. this.createAndFireBullet(fireWorldPos, weaponConfig);
  718. }
  719. }