BallController.ts 33 KB

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