BallController.ts 31 KB

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