BallController.ts 35 KB

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