BallController.ts 31 KB

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