BallController.ts 33 KB

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