BallController.ts 36 KB

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