BallController.ts 36 KB

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