BallController.ts 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  1. import { _decorator, Component, Node, Vec2, Vec3, UITransform, Collider2D, Contact2DType, IPhysics2DContact, RigidBody2D, Prefab, instantiate, find, CircleCollider2D, JsonAsset } from 'cc';
  2. import { PhysicsManager } from '../Core/PhysicsManager';
  3. import { WeaponBullet, BulletInitData, WeaponConfig } from './WeaponBullet';
  4. import EventBus, { GameEvents } from '../Core/EventBus';
  5. import { PersistentSkillManager } from '../FourUI/SkillSystem/PersistentSkillManager';
  6. import { BallAni } from '../Animations/BallAni';
  7. import { BallControllerConfig } from '../Core/ConfigManager';
  8. const { ccclass, property } = _decorator;
  9. @ccclass('BallController')
  10. export class BallController extends Component {
  11. // 球的预制体
  12. @property({
  13. type: Prefab,
  14. tooltip: '拖拽Ball预制体到这里'
  15. })
  16. public ballPrefab: Prefab = null;
  17. // 已放置方块容器节点
  18. @property({
  19. type: Node,
  20. tooltip: '拖拽PlacedBlocks节点到这里(Canvas/GameLevelUI/PlacedBlocks)'
  21. })
  22. public placedBlocksContainer: Node = null;
  23. // 球控制器配置文件
  24. @property({
  25. type: JsonAsset,
  26. tooltip: '拖拽ballController.json配置文件到这里'
  27. })
  28. public ballControllerConfig: JsonAsset = null;
  29. // 球的移动速度(从配置文件加载)
  30. public baseSpeed: number = 60;
  31. public currentSpeed: number = 60;
  32. // 反弹随机偏移最大角度(弧度)(从配置文件加载)
  33. public maxReflectionRandomness: number = 0.2;
  34. // 当前活动的球
  35. private activeBall: Node = null;
  36. // 球的方向向量
  37. private direction: Vec2 = new Vec2();
  38. // GameArea区域边界
  39. private gameBounds = {
  40. left: 0,
  41. right: 0,
  42. top: 0,
  43. bottom: 0
  44. };
  45. // 球的半径
  46. private radius: number = 0;
  47. // 配置数据
  48. private config: BallControllerConfig = null;
  49. // 是否已初始化
  50. private initialized: boolean = false;
  51. // 子弹预制体
  52. @property({
  53. type: Prefab,
  54. tooltip: '拖拽子弹预制体到这里'
  55. })
  56. public bulletPrefab: Prefab = null;
  57. // 小球是否已开始运动
  58. private ballStarted: boolean = false;
  59. // 小球暂停时记录的速度
  60. private pausedVelocity: Vec2 = new Vec2();
  61. // 标记是否处于暂停状态
  62. private isPaused: boolean = false;
  63. // 在类字段区添加
  64. private blockFireCooldown: Map<string, number> = new Map();
  65. private FIRE_COOLDOWN = 0.05;
  66. // 防围困机制配置(从配置文件加载)
  67. public antiTrapTimeWindow: number = 5.0;
  68. public antiTrapHitThreshold: number = 5;
  69. public deflectionAttemptThreshold: number = 3;
  70. public antiTrapDeflectionMultiplier: number = 3.0;
  71. // 防围困机制状态
  72. private ballHitHistory: Map<string, number[]> = new Map(); // 记录每个球的撞击时间历史
  73. private ballPhaseThrough: Map<string, number> = new Map(); // 记录每个球的穿透结束时间
  74. private ballDeflectionAttempts: Map<string, number> = new Map(); // 记录每个球的偏移尝试次数
  75. // 带尾部特效的子弹容器预制体
  76. @property({
  77. type: Prefab,
  78. tooltip: '拖拽带尾部特效的子弹容器预制体到这里(例如 PelletContainer)'
  79. })
  80. public bulletContainerPrefab: Prefab = null;
  81. start() {
  82. // 如果没有指定placedBlocksContainer,尝试找到它
  83. if (!this.placedBlocksContainer) {
  84. this.placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks');
  85. if (!this.placedBlocksContainer) {
  86. // 找不到PlacedBlocks节点,某些功能可能无法正常工作
  87. }
  88. }
  89. // 加载配置
  90. this.loadConfig();
  91. // 只进行初始设置,不创建小球
  92. this.calculateGameBounds();
  93. // 监听游戏事件
  94. this.setupEventListeners();
  95. // 监听球速技能变化并更新球速
  96. this.updateBallSpeed();
  97. }
  98. /**
  99. * 设置事件监听器
  100. */
  101. // 加载配置
  102. private loadConfig() {
  103. if (this.ballControllerConfig && this.ballControllerConfig.json) {
  104. this.config = this.ballControllerConfig.json as BallControllerConfig;
  105. this.applyConfig();
  106. console.log('[BallController] ✅ 配置文件通过装饰器加载成功:', this.config);
  107. } else {
  108. console.warn('[BallController] ⚠️ 配置文件未设置,使用默认值');
  109. // 使用默认配置
  110. this.config = {
  111. baseSpeed: 60,
  112. maxReflectionRandomness: 0.2,
  113. antiTrapTimeWindow: 5.0,
  114. antiTrapHitThreshold: 5,
  115. deflectionAttemptThreshold: 3,
  116. antiTrapDeflectionMultiplier: 3.0,
  117. FIRE_COOLDOWN: 0.05,
  118. ballRadius: 10,
  119. gravityScale: 0,
  120. linearDamping: 0,
  121. angularDamping: 0,
  122. colliderGroup: 1,
  123. colliderTag: 1,
  124. friction: 0,
  125. restitution: 1,
  126. safeDistance: 50,
  127. edgeOffset: 20,
  128. sensor: false,
  129. maxAttempts: 50
  130. };
  131. this.applyConfig();
  132. }
  133. }
  134. // 应用配置
  135. private applyConfig() {
  136. if (!this.config) return;
  137. this.baseSpeed = this.config.baseSpeed;
  138. this.currentSpeed = this.config.baseSpeed;
  139. this.maxReflectionRandomness = this.config.maxReflectionRandomness;
  140. this.antiTrapTimeWindow = this.config.antiTrapTimeWindow;
  141. this.antiTrapHitThreshold = this.config.antiTrapHitThreshold;
  142. this.deflectionAttemptThreshold = this.config.deflectionAttemptThreshold;
  143. this.antiTrapDeflectionMultiplier = this.config.antiTrapDeflectionMultiplier;
  144. this.FIRE_COOLDOWN = this.config.FIRE_COOLDOWN;
  145. console.log('BallController配置已应用:', this.config);
  146. }
  147. // 从配置中获取参数值的辅助方法
  148. private getConfigValue<T>(key: keyof BallControllerConfig, defaultValue: T): T {
  149. return this.config && this.config[key] !== undefined ? this.config[key] as T : defaultValue;
  150. }
  151. // 配置参数的getter方法
  152. private get ballRadius(): number {
  153. return this.getConfigValue('ballRadius', 10);
  154. }
  155. private get gravityScale(): number {
  156. return this.getConfigValue('gravityScale', 0);
  157. }
  158. private get linearDamping(): number {
  159. return this.getConfigValue('linearDamping', 0);
  160. }
  161. private get angularDamping(): number {
  162. return this.getConfigValue('angularDamping', 0);
  163. }
  164. private get colliderGroup(): number {
  165. return this.getConfigValue('colliderGroup', 2);
  166. }
  167. private get colliderTag(): number {
  168. return this.getConfigValue('colliderTag', 1);
  169. }
  170. private get friction(): number {
  171. return this.getConfigValue('friction', 0);
  172. }
  173. private get restitution(): number {
  174. return this.getConfigValue('restitution', 1);
  175. }
  176. private get safeDistance(): number {
  177. return this.getConfigValue('safeDistance', 50);
  178. }
  179. private get edgeOffset(): number {
  180. return this.getConfigValue('edgeOffset', 20);
  181. }
  182. private get sensor(): boolean {
  183. return this.getConfigValue('sensor', false);
  184. }
  185. private get maxAttempts(): number {
  186. return this.getConfigValue('maxAttempts', 50);
  187. }
  188. private setupEventListeners() {
  189. const eventBus = EventBus.getInstance();
  190. // 监听暂停事件
  191. eventBus.on(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
  192. // 监听恢复事件
  193. eventBus.on(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  194. // 监听重置球控制器事件
  195. eventBus.on(GameEvents.RESET_BALL_CONTROLLER, this.onResetBallControllerEvent, this);
  196. // 监听球创建事件
  197. eventBus.on(GameEvents.BALL_CREATE, this.onBallCreateEvent, this);
  198. // 监听球启动事件
  199. eventBus.on(GameEvents.BALL_START, this.onBallStartEvent, this);
  200. // 监听创建额外球事件
  201. eventBus.on(GameEvents.BALL_CREATE_ADDITIONAL, this.onBallCreateAdditionalEvent, this);
  202. }
  203. /**
  204. * 处理游戏暂停事件
  205. */
  206. private onGamePauseEvent() {
  207. console.log('[BallController] 接收到游戏暂停事件');
  208. // 根据需求,暂停时小球继续运动但不发射子弹
  209. // 子弹发射的控制已经通过GamePause.isBulletFireEnabled()实现
  210. // 这里可以添加其他暂停相关的逻辑
  211. }
  212. /**
  213. * 处理游戏恢复事件
  214. */
  215. private onGameResumeEvent() {
  216. console.log('[BallController] 接收到游戏恢复事件');
  217. // 恢复时重新启用子弹发射
  218. // 子弹发射的控制已经通过GamePause.isBulletFireEnabled()实现
  219. // 这里可以添加其他恢复相关的逻辑
  220. }
  221. /**
  222. * 处理重置球控制器事件
  223. */
  224. private onResetBallControllerEvent() {
  225. console.log('[BallController] 接收到重置球控制器事件');
  226. this.resetBallController();
  227. }
  228. /**
  229. * 处理球创建事件
  230. */
  231. private onBallCreateEvent() {
  232. console.log('[BallController] 接收到球创建事件');
  233. this.createBall();
  234. }
  235. /**
  236. * 处理球启动事件
  237. */
  238. private onBallStartEvent() {
  239. console.log('[BallController] 接收到球启动事件');
  240. this.startBall();
  241. }
  242. /**
  243. * 处理创建额外球事件
  244. */
  245. private onBallCreateAdditionalEvent() {
  246. console.log('[BallController] 接收到创建额外球事件');
  247. this.createAdditionalBall();
  248. }
  249. // 计算游戏边界(使用GameArea节点)
  250. calculateGameBounds() {
  251. // 获取GameArea节点
  252. const gameArea = find('Canvas/GameLevelUI/GameArea');
  253. if (!gameArea) {
  254. return;
  255. }
  256. const gameAreaUI = gameArea.getComponent(UITransform);
  257. if (!gameAreaUI) {
  258. return;
  259. }
  260. // 获取GameArea的尺寸
  261. const areaWidth = gameAreaUI.width;
  262. const areaHeight = gameAreaUI.height;
  263. // 获取GameArea的世界坐标位置
  264. const worldPos = gameArea.worldPosition;
  265. // 计算GameArea的世界坐标边界
  266. this.gameBounds.left = worldPos.x - areaWidth / 2;
  267. this.gameBounds.right = worldPos.x + areaWidth / 2;
  268. this.gameBounds.bottom = worldPos.y - areaHeight / 2;
  269. this.gameBounds.top = worldPos.y + areaHeight / 2;
  270. }
  271. // 创建小球
  272. createBall() {
  273. if (!this.ballPrefab) {
  274. console.error('[BallController] ballPrefab 未设置,无法创建小球');
  275. return;
  276. }
  277. // 实例化小球
  278. this.activeBall = instantiate(this.ballPrefab);
  279. if (!this.activeBall) {
  280. console.error('[BallController] 小球实例化失败');
  281. return;
  282. }
  283. // 将小球添加到GameArea中
  284. const gameArea = find('Canvas/GameLevelUI/GameArea');
  285. if (gameArea) {
  286. gameArea.addChild(this.activeBall);
  287. } else {
  288. console.warn('[BallController] 未找到GameArea,将小球添加到当前节点');
  289. this.node.addChild(this.activeBall);
  290. }
  291. // 随机位置小球
  292. this.positionBallRandomly();
  293. // 设置球的半径
  294. const transform = this.activeBall.getComponent(UITransform);
  295. if (transform) {
  296. this.radius = transform.width / 2;
  297. } else {
  298. this.radius = 25; // 默认半径
  299. }
  300. // 确保有碰撞组件
  301. this.setupCollider();
  302. // 注意:不在这里初始化方向,等待 startBall() 调用
  303. this.initialized = true;
  304. }
  305. // 创建额外的小球(不替换现有的小球)
  306. public createAdditionalBall() {
  307. if (!this.ballPrefab) {
  308. console.error('无法创建额外小球:ballPrefab 未设置');
  309. return;
  310. }
  311. // 实例化新的小球
  312. const newBall = instantiate(this.ballPrefab);
  313. newBall.name = 'AdditionalBall';
  314. // 将小球添加到GameArea中
  315. const gameArea = find('Canvas/GameLevelUI/GameArea');
  316. if (gameArea) {
  317. gameArea.addChild(newBall);
  318. } else {
  319. this.node.addChild(newBall);
  320. }
  321. // 随机位置小球
  322. this.positionAdditionalBall(newBall);
  323. // 设置球的碰撞组件
  324. this.setupBallCollider(newBall);
  325. // 设置初始方向和速度
  326. this.initializeBallDirection(newBall);
  327. console.log('创建了额外的小球');
  328. return newBall;
  329. }
  330. // 为额外小球设置随机位置
  331. private positionAdditionalBall(ball: Node) {
  332. if (!ball) return;
  333. const transform = ball.getComponent(UITransform);
  334. const ballRadius = transform ? transform.width / 2 : this.ballRadius;
  335. // 计算可生成的范围(考虑小球半径,避免生成在边缘)
  336. const minX = this.gameBounds.left + ballRadius + this.edgeOffset;
  337. const maxX = this.gameBounds.right - ballRadius - this.edgeOffset;
  338. const minY = this.gameBounds.bottom + ballRadius + this.edgeOffset;
  339. const maxY = this.gameBounds.top - ballRadius - this.edgeOffset;
  340. // 获取GameArea节点
  341. const gameArea = find('Canvas/GameLevelUI/GameArea');
  342. if (!gameArea) {
  343. return;
  344. }
  345. // 随机生成位置
  346. const randomX = Math.random() * (maxX - minX) + minX;
  347. const randomY = Math.random() * (maxY - minY) + minY;
  348. // 将世界坐标转换为相对于GameArea的本地坐标
  349. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  350. ball.position = localPos;
  351. }
  352. // 为额外小球设置碰撞组件
  353. private setupBallCollider(ball: Node) {
  354. // 确保有碰撞组件
  355. let collider = ball.getComponent(CircleCollider2D);
  356. if (!collider) {
  357. collider = ball.addComponent(CircleCollider2D);
  358. }
  359. // 设置碰撞属性(使用配置值)
  360. collider.radius = this.ballRadius;
  361. collider.group = this.colliderGroup;
  362. collider.tag = this.colliderTag;
  363. collider.sensor = this.sensor;
  364. collider.friction = this.friction;
  365. collider.restitution = this.restitution;
  366. // 添加刚体组件
  367. let rigidBody = ball.getComponent(RigidBody2D);
  368. if (!rigidBody) {
  369. rigidBody = ball.addComponent(RigidBody2D);
  370. }
  371. // 设置刚体属性(使用配置值)
  372. rigidBody.type = 2; // 2 = 动态刚体
  373. rigidBody.allowSleep = false;
  374. rigidBody.gravityScale = this.gravityScale;
  375. rigidBody.linearDamping = this.linearDamping;
  376. rigidBody.angularDamping = this.angularDamping;
  377. rigidBody.fixedRotation = true;
  378. rigidBody.enabledContactListener = true; // 启用碰撞监听
  379. // 注意:不需要为每个小球单独添加碰撞回调,
  380. // 因为我们使用的是全局物理系统回调
  381. }
  382. // 为额外小球初始化方向和速度
  383. private initializeBallDirection(ball: Node) {
  384. // 随机初始方向
  385. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  386. const direction = new Vec2(Math.cos(angle), Math.sin(angle)).normalize();
  387. // 设置初始速度
  388. const rigidBody = ball.getComponent(RigidBody2D);
  389. if (rigidBody) {
  390. rigidBody.linearVelocity = new Vec2(
  391. direction.x * this.currentSpeed,
  392. direction.y * this.currentSpeed
  393. );
  394. }
  395. }
  396. // 检查所有已放置方块的碰撞体组件
  397. private checkBlockColliders() {
  398. if (!this.placedBlocksContainer) {
  399. return;
  400. }
  401. if (!this.placedBlocksContainer.isValid) {
  402. return;
  403. }
  404. const blocks = [];
  405. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  406. const block = this.placedBlocksContainer.children[i];
  407. if (block.name.includes('Block') || block.getChildByName('B1')) {
  408. blocks.push(block);
  409. }
  410. }
  411. let fixedCount = 0;
  412. for (let i = 0; i < blocks.length; i++) {
  413. const block = blocks[i];
  414. // 检查方块本身的碰撞体
  415. const blockCollider = block.getComponent(Collider2D);
  416. if (blockCollider) {
  417. // 🔧 自动修复碰撞组设置
  418. if (blockCollider.group !== 2) {
  419. blockCollider.group = 2; // 设置为Block组
  420. fixedCount++;
  421. }
  422. // 确保不是传感器
  423. if (blockCollider.sensor) {
  424. blockCollider.sensor = false;
  425. }
  426. }
  427. // 检查B1子节点的碰撞体
  428. const b1Node = block.getChildByName('B1');
  429. if (b1Node) {
  430. const b1Collider = b1Node.getComponent(Collider2D);
  431. if (b1Collider) {
  432. // 🔧 修复B1子节点的碰撞设置
  433. if (b1Collider.group !== 2) {
  434. b1Collider.group = 2; // 设置为Block组
  435. fixedCount++;
  436. }
  437. // 确保B1不是传感器(需要实际碰撞)
  438. if (b1Collider.sensor) {
  439. b1Collider.sensor = false;
  440. }
  441. }
  442. }
  443. // 检查Weapon子节点
  444. const weaponNode = this.findWeaponNode(block);
  445. if (weaponNode) {
  446. // 武器节点存在
  447. }
  448. }
  449. }
  450. // 随机位置小球
  451. positionBallRandomly() {
  452. if (!this.activeBall) return;
  453. const transform = this.activeBall.getComponent(UITransform);
  454. const ballRadius = transform ? transform.width / 2 : this.ballRadius;
  455. // 计算可生成的范围(考虑小球半径,避免生成在边缘)
  456. const minX = this.gameBounds.left + ballRadius + this.edgeOffset; // 额外偏移,避免生成在边缘
  457. const maxX = this.gameBounds.right - ballRadius - this.edgeOffset;
  458. const minY = this.gameBounds.bottom + ballRadius + this.edgeOffset;
  459. const maxY = this.gameBounds.top - ballRadius - this.edgeOffset;
  460. // 获取GameArea节点
  461. const gameArea = find('Canvas/GameLevelUI/GameArea');
  462. if (!gameArea) {
  463. return;
  464. }
  465. // 查找PlacedBlocks节点,它包含所有放置的方块
  466. if (!this.placedBlocksContainer) {
  467. this.setRandomPositionDefault(minX, maxX, minY, maxY);
  468. return;
  469. }
  470. if (!this.placedBlocksContainer.isValid) {
  471. this.setRandomPositionDefault(minX, maxX, minY, maxY);
  472. return;
  473. }
  474. // 获取所有已放置的方块
  475. const placedBlocks = [];
  476. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  477. const block = this.placedBlocksContainer.children[i];
  478. // 检查是否是方块节点(通常以Block命名或有特定标识)
  479. if (block.name.includes('Block') || block.getChildByName('B1')) {
  480. placedBlocks.push(block);
  481. }
  482. }
  483. // 如果没有方块,使用默认随机位置
  484. if (placedBlocks.length === 0) {
  485. this.setRandomPositionDefault(minX, maxX, minY, maxY);
  486. return;
  487. }
  488. // 尝试找到一个不与任何方块重叠的位置
  489. let validPosition = false;
  490. let attempts = 0;
  491. const maxAttempts = this.maxAttempts; // 从配置中获取最大尝试次数
  492. let randomX, randomY;
  493. while (!validPosition && attempts < maxAttempts) {
  494. // 随机生成位置
  495. randomX = Math.random() * (maxX - minX) + minX;
  496. randomY = Math.random() * (maxY - minY) + minY;
  497. // 检查是否与任何方块重叠
  498. let overlapping = false;
  499. for (const block of placedBlocks) {
  500. // 获取方块的世界坐标
  501. const blockWorldPos = block.worldPosition;
  502. // 计算小球与方块的距离
  503. const distance = Math.sqrt(
  504. Math.pow(randomX - blockWorldPos.x, 2) +
  505. Math.pow(randomY - blockWorldPos.y, 2)
  506. );
  507. // 获取方块的尺寸
  508. const blockTransform = block.getComponent(UITransform);
  509. const blockSize = blockTransform ?
  510. Math.max(blockTransform.width, blockTransform.height) / 2 : this.safeDistance;
  511. // 如果距离小于小球半径+方块尺寸的一半+安全距离,认为重叠
  512. if (distance < ballRadius + blockSize + this.safeDistance) {
  513. overlapping = true;
  514. break;
  515. }
  516. }
  517. // 如果没有重叠,找到了有效位置
  518. if (!overlapping) {
  519. validPosition = true;
  520. }
  521. attempts++;
  522. }
  523. // 如果找不到有效位置,使用默认位置(游戏区域底部中心)
  524. if (!validPosition) {
  525. randomX = (this.gameBounds.left + this.gameBounds.right) / 2;
  526. randomY = this.gameBounds.bottom + ballRadius + this.safeDistance; // 底部上方安全距离单位
  527. }
  528. // 将世界坐标转换为相对于GameArea的本地坐标
  529. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  530. this.activeBall.position = localPos;
  531. }
  532. // 设置默认随机位置
  533. setRandomPositionDefault(minX, maxX, minY, maxY) {
  534. // 随机生成位置
  535. const randomX = Math.random() * (maxX - minX) + minX;
  536. const randomY = Math.random() * (maxY - minY) + minY;
  537. // 将世界坐标转换为相对于GameArea的本地坐标
  538. const gameArea = find('Canvas/GameLevelUI/GameArea');
  539. if (gameArea) {
  540. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  541. this.activeBall.position = localPos;
  542. } else {
  543. // 直接设置位置(不太准确,但作为后备)
  544. this.activeBall.position = new Vec3(randomX - this.gameBounds.left, randomY - this.gameBounds.bottom, 0);
  545. }
  546. }
  547. // 设置碰撞组件
  548. setupCollider() {
  549. if (!this.activeBall) return;
  550. // 确保小球有刚体组件
  551. let rigidBody = this.activeBall.getComponent(RigidBody2D);
  552. if (!rigidBody) {
  553. rigidBody = this.activeBall.addComponent(RigidBody2D);
  554. rigidBody.type = 2; // Dynamic
  555. rigidBody.gravityScale = this.gravityScale; // 从配置获取重力缩放
  556. rigidBody.enabledContactListener = true; // 启用碰撞监听
  557. rigidBody.fixedRotation = true; // 固定旋转
  558. rigidBody.allowSleep = false; // 不允许休眠
  559. rigidBody.linearDamping = this.linearDamping; // 从配置获取线性阻尼
  560. rigidBody.angularDamping = this.angularDamping; // 从配置获取角阻尼
  561. } else {
  562. // 确保已有的刚体组件设置正确
  563. rigidBody.enabledContactListener = true;
  564. rigidBody.gravityScale = this.gravityScale;
  565. rigidBody.linearDamping = this.linearDamping; // 从配置获取线性阻尼
  566. rigidBody.angularDamping = this.angularDamping; // 从配置获取角阻尼
  567. rigidBody.allowSleep = false; // 不允许休眠
  568. }
  569. // 确保小球有碰撞组件
  570. let collider = this.activeBall.getComponent(CircleCollider2D);
  571. if (!collider) {
  572. collider = this.activeBall.addComponent(CircleCollider2D);
  573. collider.radius = this.radius || this.ballRadius; // 使用已计算的半径或配置值
  574. collider.tag = this.colliderTag; // 从配置获取小球标签
  575. collider.group = this.colliderGroup; // 从配置获取碰撞组
  576. collider.sensor = this.sensor; // 从配置获取传感器设置
  577. collider.friction = this.friction; // 从配置获取摩擦系数
  578. collider.restitution = this.restitution; // 从配置获取恢复系数
  579. } else {
  580. // 确保已有的碰撞组件设置正确
  581. collider.sensor = this.sensor;
  582. collider.restitution = this.restitution;
  583. collider.group = this.colliderGroup; // 从配置获取碰撞组
  584. collider.tag = this.colliderTag; // 从配置获取标签
  585. }
  586. // === 使用全局回调监听器 ===
  587. const physics = PhysicsManager.getInstance()?.getSystem();
  588. if (physics) {
  589. // 先移除旧监听,避免重复注册
  590. physics.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  591. physics.off(Contact2DType.END_CONTACT, this.onEndContact, this);
  592. physics.off(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
  593. physics.off(Contact2DType.POST_SOLVE, this.onPostSolve, this);
  594. physics.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  595. physics.on(Contact2DType.END_CONTACT, this.onEndContact, this);
  596. physics.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
  597. physics.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
  598. }
  599. }
  600. // 碰撞回调 - 处理小球与方块以及小球之间的碰撞
  601. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  602. // 检查是否为小球之间的碰撞
  603. if (selfCollider.group === 1 && otherCollider.group === 1) {
  604. // 小球之间的碰撞 - 防止速度改变
  605. this.handleBallToBallCollision(selfCollider, otherCollider, contact);
  606. return;
  607. }
  608. // 判断哪个是小球,哪个是碰撞对象
  609. let ballNode: Node = null;
  610. let otherNode: Node = null;
  611. // 检查self是否为小球(组1)
  612. if (selfCollider.group === 1) {
  613. ballNode = selfCollider.node;
  614. otherNode = otherCollider.node;
  615. }
  616. // 检查other是否为小球(组1)
  617. else if (otherCollider.group === 1) {
  618. ballNode = otherCollider.node;
  619. otherNode = selfCollider.node;
  620. }
  621. // 如果没有找到小球,跳过处理
  622. if (!ballNode || !otherNode) {
  623. return;
  624. }
  625. // 检查是否为方块碰撞
  626. const nodeName = otherNode.name;
  627. const nodePath = this.getNodePath(otherNode);
  628. const hasWeaponChild = otherNode.getChildByName('Weapon') !== null;
  629. const isBlock =
  630. nodeName.includes('Block') ||
  631. nodePath.includes('Block') ||
  632. hasWeaponChild;
  633. // 如果是方块碰撞,检查防围困机制
  634. if (isBlock) {
  635. const ballId = ballNode.uuid;
  636. const currentTime = performance.now() / 1000; // 转换为秒
  637. // 检查是否处于穿透状态
  638. const phaseThroughEndTime = this.ballPhaseThrough.get(ballId);
  639. if (phaseThroughEndTime && currentTime < phaseThroughEndTime) {
  640. // 处于穿透状态,忽略碰撞但仍播放特效
  641. const ballAni = BallAni.getInstance();
  642. if (ballAni) {
  643. let contactPos: Vec3 = null;
  644. if (contact && (contact as any).getWorldManifold) {
  645. const wm = (contact as any).getWorldManifold();
  646. if (wm && wm.points && wm.points.length > 0) {
  647. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  648. }
  649. }
  650. if (!contactPos) {
  651. contactPos = otherNode.worldPosition.clone();
  652. }
  653. ballAni.playImpactEffect(contactPos);
  654. }
  655. // 禁用碰撞
  656. if (contact) {
  657. contact.disabled = true;
  658. }
  659. return;
  660. }
  661. // 记录撞击历史
  662. if (!this.ballHitHistory.has(ballId)) {
  663. this.ballHitHistory.set(ballId, []);
  664. }
  665. const hitHistory = this.ballHitHistory.get(ballId);
  666. hitHistory.push(currentTime);
  667. // 清理过期的撞击记录
  668. const timeThreshold = currentTime - this.antiTrapTimeWindow;
  669. while (hitHistory.length > 0 && hitHistory[0] < timeThreshold) {
  670. hitHistory.shift();
  671. }
  672. // 检查是否达到防围困条件
  673. if (hitHistory.length >= this.antiTrapHitThreshold) {
  674. // 获取当前偏移尝试次数
  675. const deflectionAttempts = this.ballDeflectionAttempts.get(ballId) || 0;
  676. if (deflectionAttempts < this.deflectionAttemptThreshold) {
  677. // 优先使用偏移方式
  678. this.ballDeflectionAttempts.set(ballId, deflectionAttempts + 1);
  679. // 应用增强偏移反弹
  680. const rigidBody = ballNode.getComponent(RigidBody2D);
  681. if (rigidBody && contact) {
  682. // 获取碰撞法线
  683. let normal = new Vec2(0, 1);
  684. if ((contact as any).getWorldManifold) {
  685. const wm = (contact as any).getWorldManifold();
  686. if (wm && wm.normal) {
  687. normal = new Vec2(wm.normal.x, wm.normal.y);
  688. }
  689. }
  690. // 计算增强偏移反弹方向
  691. const currentVelocity = rigidBody.linearVelocity;
  692. const currentDirection = new Vec2(currentVelocity.x, currentVelocity.y).normalize();
  693. const newDirection = this.calculateAntiTrapReflection(currentDirection, normal);
  694. // 应用新的速度方向
  695. const speed = currentVelocity.length();
  696. rigidBody.linearVelocity = new Vec2(newDirection.x * speed, newDirection.y * speed);
  697. console.log(`Ball ${ballId} applied anti-trap deflection (attempt ${deflectionAttempts + 1}/${this.deflectionAttemptThreshold})`);
  698. }
  699. // 清空撞击历史,给偏移一个机会
  700. hitHistory.length = 0;
  701. } else {
  702. // 偏移尝试次数已达上限,使用穿透
  703. this.ballPhaseThrough.set(ballId, currentTime + 0.5);
  704. // 重置偏移尝试次数
  705. this.ballDeflectionAttempts.set(ballId, 0);
  706. // 清空撞击历史
  707. hitHistory.length = 0;
  708. // 禁用当前碰撞
  709. if (contact) {
  710. contact.disabled = true;
  711. }
  712. console.log(`Ball ${ballId} entered phase-through mode after ${this.deflectionAttemptThreshold} deflection attempts failed`);
  713. return;
  714. }
  715. }
  716. }
  717. // 计算碰撞世界坐标
  718. let contactPos: Vec3 = null;
  719. if (contact && (contact as any).getWorldManifold) {
  720. const wm = (contact as any).getWorldManifold();
  721. if (wm && wm.points && wm.points.length > 0) {
  722. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  723. }
  724. }
  725. if (!contactPos) {
  726. contactPos = otherNode.worldPosition.clone();
  727. }
  728. // 播放撞击特效 - 对所有碰撞都播放特效
  729. const ballAni = BallAni.getInstance();
  730. if (ballAni) {
  731. ballAni.playImpactEffect(contactPos);
  732. }
  733. if (isBlock) {
  734. // 播放方块撞击动画
  735. if (ballAni) {
  736. ballAni.playBlockHitAnimation(otherNode);
  737. }
  738. // 通过事件检查是否可以发射子弹
  739. const eventBus = EventBus.getInstance();
  740. let canFire = true;
  741. // 发送检查事件,如果有监听器返回false则不发射
  742. eventBus.emit(GameEvents.BALL_FIRE_BULLET, { canFire: (value: boolean) => { canFire = value; } });
  743. if (canFire) {
  744. const now = performance.now();
  745. const lastTime = this.blockFireCooldown.get(otherNode.uuid) || 0;
  746. if (now - lastTime > this.FIRE_COOLDOWN * 1000) {
  747. this.blockFireCooldown.set(otherNode.uuid, now);
  748. this.fireBulletAt(otherNode, contactPos);
  749. }
  750. }
  751. }
  752. }
  753. /**
  754. * 处理小球之间的碰撞 - 保持恒定速度
  755. */
  756. private handleBallToBallCollision(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  757. const ball1 = selfCollider.node;
  758. const ball2 = otherCollider.node;
  759. const rigidBody1 = ball1.getComponent(RigidBody2D);
  760. const rigidBody2 = ball2.getComponent(RigidBody2D);
  761. if (!rigidBody1 || !rigidBody2) {
  762. return;
  763. }
  764. // 计算碰撞位置并播放撞击特效
  765. let contactPos: Vec3 = null;
  766. if (contact && (contact as any).getWorldManifold) {
  767. const wm = (contact as any).getWorldManifold();
  768. if (wm && wm.points && wm.points.length > 0) {
  769. contactPos = new Vec3(wm.points[0].x, wm.points[0].y, 0);
  770. }
  771. }
  772. if (!contactPos) {
  773. // 使用两个小球位置的中点作为碰撞位置
  774. const pos1 = ball1.worldPosition;
  775. const pos2 = ball2.worldPosition;
  776. contactPos = new Vec3(
  777. (pos1.x + pos2.x) / 2,
  778. (pos1.y + pos2.y) / 2,
  779. 0
  780. );
  781. }
  782. // 播放撞击特效
  783. const ballAni = BallAni.getInstance();
  784. if (ballAni) {
  785. ballAni.playImpactEffect(contactPos);
  786. }
  787. // 获取碰撞前的速度
  788. const velocity1 = rigidBody1.linearVelocity.clone();
  789. const velocity2 = rigidBody2.linearVelocity.clone();
  790. // 计算速度大小
  791. const speed1 = Math.sqrt(velocity1.x * velocity1.x + velocity1.y * velocity1.y);
  792. const speed2 = Math.sqrt(velocity2.x * velocity2.x + velocity2.y * velocity2.y);
  793. // 延迟一帧后恢复正确的速度,避免物理引擎的速度改变
  794. this.scheduleOnce(() => {
  795. if (ball1.isValid && rigidBody1.isValid) {
  796. const currentVel1 = rigidBody1.linearVelocity;
  797. const currentSpeed1 = Math.sqrt(currentVel1.x * currentVel1.x + currentVel1.y * currentVel1.y);
  798. // 如果速度发生了显著变化,恢复到目标速度
  799. if (Math.abs(currentSpeed1 - this.currentSpeed) > 5) {
  800. const normalizedVel1 = currentVel1.clone().normalize();
  801. rigidBody1.linearVelocity = new Vec2(
  802. normalizedVel1.x * this.currentSpeed,
  803. normalizedVel1.y * this.currentSpeed
  804. );
  805. }
  806. }
  807. if (ball2.isValid && rigidBody2.isValid) {
  808. const currentVel2 = rigidBody2.linearVelocity;
  809. const currentSpeed2 = Math.sqrt(currentVel2.x * currentVel2.x + currentVel2.y * currentVel2.y);
  810. // 如果速度发生了显著变化,恢复到目标速度
  811. if (Math.abs(currentSpeed2 - this.currentSpeed) > 5) {
  812. const normalizedVel2 = currentVel2.clone().normalize();
  813. rigidBody2.linearVelocity = new Vec2(
  814. normalizedVel2.x * this.currentSpeed,
  815. normalizedVel2.y * this.currentSpeed
  816. );
  817. }
  818. }
  819. }, 0.016); // 约一帧的时间
  820. }
  821. // 碰撞结束事件 - 简化版本
  822. onEndContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  823. // Debug log removed
  824. }
  825. // 碰撞预处理事件 - 简化版本
  826. onPreSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  827. // console.log('⚙️ 碰撞预处理:', otherCollider.node.name);
  828. }
  829. // 碰撞后处理事件 - 简化版本
  830. onPostSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  831. // console.log('✅ 碰撞后处理:', otherCollider.node.name);
  832. }
  833. // 计算反射向量
  834. calculateReflection(direction: Vec2, normal: Vec2): Vec2 {
  835. // 使用反射公式: R = V - 2(V·N)N
  836. const dot = direction.x * normal.x + direction.y * normal.y;
  837. const reflection = new Vec2(
  838. direction.x - 2 * dot * normal.x,
  839. direction.y - 2 * dot * normal.y
  840. );
  841. reflection.normalize();
  842. // 添加一些随机性,避免重复的反弹路径
  843. const randomAngle = (Math.random() - 0.5) * this.maxReflectionRandomness; // 随机角度
  844. const cos = Math.cos(randomAngle);
  845. const sin = Math.sin(randomAngle);
  846. // 应用随机旋转
  847. const randomizedReflection = new Vec2(
  848. reflection.x * cos - reflection.y * sin,
  849. reflection.x * sin + reflection.y * cos
  850. );
  851. // 确保反射方向不会太接近水平或垂直方向
  852. // 这有助于避免球在水平或垂直方向上来回反弹
  853. const minAngleFromAxis = 0.1; // 约5.7度
  854. // 检查是否接近水平方向
  855. if (Math.abs(randomizedReflection.y) < minAngleFromAxis) {
  856. // 调整y分量,使其远离水平方向
  857. const sign = randomizedReflection.y >= 0 ? 1 : -1;
  858. randomizedReflection.y = sign * (minAngleFromAxis + Math.random() * 0.1);
  859. // 重新归一化
  860. randomizedReflection.normalize();
  861. }
  862. // 检查是否接近垂直方向
  863. if (Math.abs(randomizedReflection.x) < minAngleFromAxis) {
  864. // 调整x分量,使其远离垂直方向
  865. const sign = randomizedReflection.x >= 0 ? 1 : -1;
  866. randomizedReflection.x = sign * (minAngleFromAxis + Math.random() * 0.1);
  867. // 重新归一化
  868. randomizedReflection.normalize();
  869. }
  870. randomizedReflection.normalize();
  871. // Debug log removed
  872. return randomizedReflection;
  873. }
  874. /**
  875. * 计算防围困增强偏移反弹方向
  876. * @param direction 当前方向
  877. * @param normal 碰撞法线
  878. * @returns 增强偏移后的反弹方向
  879. */
  880. calculateAntiTrapReflection(direction: Vec2, normal: Vec2): Vec2 {
  881. // 使用反射公式: R = V - 2(V·N)N
  882. const dot = direction.x * normal.x + direction.y * normal.y;
  883. const reflection = new Vec2(
  884. direction.x - 2 * dot * normal.x,
  885. direction.y - 2 * dot * normal.y
  886. );
  887. reflection.normalize();
  888. // 应用更强的随机偏移来帮助脱困
  889. const enhancedRandomness = this.maxReflectionRandomness * this.antiTrapDeflectionMultiplier;
  890. const randomAngle = (Math.random() - 0.5) * enhancedRandomness;
  891. const cos = Math.cos(randomAngle);
  892. const sin = Math.sin(randomAngle);
  893. // 应用随机旋转
  894. const randomizedReflection = new Vec2(
  895. reflection.x * cos - reflection.y * sin,
  896. reflection.x * sin + reflection.y * cos
  897. );
  898. // 更强的轴向偏移避免
  899. const minAngleFromAxis = 0.3; // 约17度,比普通反弹更大的偏移
  900. // 检查是否接近水平方向
  901. if (Math.abs(randomizedReflection.y) < minAngleFromAxis) {
  902. const sign = randomizedReflection.y >= 0 ? 1 : -1;
  903. randomizedReflection.y = sign * (minAngleFromAxis + Math.random() * 0.2);
  904. randomizedReflection.normalize();
  905. }
  906. // 检查是否接近垂直方向
  907. if (Math.abs(randomizedReflection.x) < minAngleFromAxis) {
  908. const sign = randomizedReflection.x >= 0 ? 1 : -1;
  909. randomizedReflection.x = sign * (minAngleFromAxis + Math.random() * 0.2);
  910. randomizedReflection.normalize();
  911. }
  912. randomizedReflection.normalize();
  913. console.log(`Applied anti-trap enhanced deflection with angle: ${randomAngle}`);
  914. return randomizedReflection;
  915. }
  916. /**
  917. * 从方块武器发射子弹攻击敌人 - 重构版本
  918. * 现在直接创建子弹实例并使用BulletController的实例方法
  919. * @param blockNode 激活的方块节点
  920. */
  921. fireBullet(blockNode: Node) {
  922. // Debug logs removed
  923. // 检查子弹预制体是否存在
  924. if (!this.bulletPrefab) {
  925. return;
  926. }
  927. // 查找方块中的Weapon节点
  928. const weaponNode = this.findWeaponNode(blockNode);
  929. if (!weaponNode) {
  930. const blockWorldPos = blockNode.worldPosition;
  931. const weaponConfig2: WeaponConfig | null = (blockNode as any)['weaponConfig'] || null;
  932. this.createAndFireBullet(blockWorldPos, weaponConfig2);
  933. return;
  934. }
  935. // 获取武器的世界坐标作为发射位置
  936. let firePosition: Vec3;
  937. try {
  938. firePosition = weaponNode.worldPosition;
  939. } catch (error) {
  940. // 备用方案:使用方块坐标
  941. firePosition = blockNode.worldPosition;
  942. }
  943. // 创建并发射子弹
  944. const weaponConfig: WeaponConfig | null = (blockNode as any)['weaponConfig'] || null;
  945. this.createAndFireBullet(firePosition, weaponConfig);
  946. }
  947. /**
  948. * 创建并发射子弹 - 使用新的WeaponBullet系统
  949. * @param firePosition 发射位置(世界坐标)
  950. * @param weaponConfig 武器配置
  951. */
  952. private createAndFireBullet(firePosition: Vec3, weaponConfig: WeaponConfig | null) {
  953. // 确保武器配置加载
  954. WeaponBullet.loadWeaponsData().then(() => {
  955. // 默认使用毛豆射手配置,后续可以根据方块类型动态选择
  956. const defaultWeaponId = 'pea_shooter';
  957. const finalConfig = weaponConfig || WeaponBullet.getWeaponConfig(defaultWeaponId);
  958. if (!finalConfig) {
  959. return;
  960. }
  961. // 创建子弹初始化数据
  962. const initData: BulletInitData = {
  963. weaponId: finalConfig.id,
  964. firePosition: firePosition,
  965. autoTarget: true,
  966. weaponConfig: finalConfig
  967. };
  968. // 验证初始化数据
  969. if (!WeaponBullet.validateInitData(initData)) {
  970. return;
  971. }
  972. // 判断是否为多发子弹(散射/连发等)
  973. const countCfg = finalConfig.bulletConfig.count;
  974. const isMultiShot = countCfg && countCfg.type !== 'single' && countCfg.amount > 1;
  975. // 查找GameArea(子弹统一添加到此节点)
  976. const gameArea = find('Canvas/GameLevelUI/GameArea');
  977. if (!gameArea) {
  978. return;
  979. }
  980. // === 根据武器配置选择合适的预制体 ===
  981. const needsTrail = !!(finalConfig.bulletConfig?.visual?.trailEffect);
  982. const prefabToUse: Prefab = (needsTrail && this.bulletContainerPrefab) ? this.bulletContainerPrefab : this.bulletPrefab;
  983. if (!prefabToUse) {
  984. return; // 如果没有可用的预制体则直接退出
  985. }
  986. if (isMultiShot) {
  987. // 使用批量创建逻辑
  988. const bullets = WeaponBullet.createBullets(initData, prefabToUse as any);
  989. bullets.forEach(b => {
  990. gameArea.addChild(b);
  991. });
  992. } else {
  993. // 单发逻辑(沿用原流程)
  994. const bullet = instantiate(prefabToUse);
  995. if (!bullet) {
  996. return;
  997. }
  998. gameArea.addChild(bullet);
  999. let weaponBullet = bullet.getComponent(WeaponBullet);
  1000. if (!weaponBullet) {
  1001. weaponBullet = bullet.addComponent(WeaponBullet);
  1002. }
  1003. weaponBullet.init(initData);
  1004. }
  1005. }).catch(error => {
  1006. // 武器配置加载失败
  1007. });
  1008. }
  1009. // 递归查找Weapon节点
  1010. private findWeaponNode(node: Node): Node | null {
  1011. // logs removed
  1012. // 先检查当前节点是否有Weapon子节点
  1013. const weaponNode = node.getChildByName('Weapon');
  1014. if (weaponNode) {
  1015. return weaponNode;
  1016. }
  1017. // 如果没有,递归检查所有子节点
  1018. for (let i = 0; i < node.children.length; i++) {
  1019. const child = node.children[i];
  1020. const foundWeapon = this.findWeaponNode(child);
  1021. if (foundWeapon) {
  1022. return foundWeapon;
  1023. }
  1024. }
  1025. // 如果都没找到,返回null
  1026. return null;
  1027. }
  1028. // 获取节点的完整路径
  1029. private getNodePath(node: Node): string {
  1030. let path = node.name;
  1031. let current = node;
  1032. while (current.parent) {
  1033. current = current.parent;
  1034. path = current.name + '/' + path;
  1035. }
  1036. return path;
  1037. }
  1038. update(dt: number) {
  1039. // 只有当小球已启动时才执行运动逻辑
  1040. if (!this.ballStarted || !this.initialized) {
  1041. return;
  1042. }
  1043. // 维持所有小球的恒定速度
  1044. this.maintainAllBallsSpeed();
  1045. // 清理过期的防围困状态
  1046. this.cleanupExpiredAntiTrapStates();
  1047. // 定期检查小球是否接近方块但没有触发碰撞(调试用)
  1048. if (this.activeBall && this.activeBall.isValid) {
  1049. this.debugCheckNearBlocks();
  1050. }
  1051. }
  1052. /**
  1053. * 维持所有小球的恒定速度
  1054. */
  1055. private maintainAllBallsSpeed() {
  1056. // 维持主小球速度
  1057. if (this.activeBall && this.activeBall.isValid) {
  1058. this.maintainBallSpeed(this.activeBall);
  1059. }
  1060. // 维持额外小球的速度
  1061. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1062. if (gameArea) {
  1063. const additionalBalls = gameArea.children.filter(child =>
  1064. child.name === 'AdditionalBall' && child.isValid
  1065. );
  1066. for (const ball of additionalBalls) {
  1067. this.maintainBallSpeed(ball);
  1068. }
  1069. }
  1070. }
  1071. /**
  1072. * 维持单个小球的恒定速度
  1073. */
  1074. private maintainBallSpeed(ball: Node) {
  1075. const rigidBody = ball.getComponent(RigidBody2D);
  1076. if (!rigidBody) return;
  1077. // 获取当前速度
  1078. const currentVelocity = rigidBody.linearVelocity;
  1079. const speed = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
  1080. // 如果速度过低或过高,重新设置速度以维持恒定运动
  1081. if (speed < this.currentSpeed * 0.85 || speed > this.currentSpeed * 1.15) {
  1082. // 保持当前方向,但调整速度大小
  1083. if (speed > 0.1) {
  1084. const normalizedVelocity = currentVelocity.clone().normalize();
  1085. rigidBody.linearVelocity = new Vec2(
  1086. normalizedVelocity.x * this.currentSpeed,
  1087. normalizedVelocity.y * this.currentSpeed
  1088. );
  1089. } else {
  1090. // 如果速度几乎为0,给一个随机方向
  1091. const angle = Math.random() * Math.PI * 2;
  1092. rigidBody.linearVelocity = new Vec2(
  1093. Math.cos(angle) * this.currentSpeed,
  1094. Math.sin(angle) * this.currentSpeed
  1095. );
  1096. }
  1097. }
  1098. // 更新主小球的方向向量(用于其他逻辑)
  1099. if (ball === this.activeBall && speed > 1.0) {
  1100. this.direction.x = currentVelocity.x / speed;
  1101. this.direction.y = currentVelocity.y / speed;
  1102. }
  1103. }
  1104. // 调试方法:检查小球是否接近方块但没有触发物理碰撞
  1105. private debugCheckCounter = 0;
  1106. private debugCheckNearBlocks() {
  1107. this.debugCheckCounter++;
  1108. // 每60帧(约1秒)检查一次
  1109. if (this.debugCheckCounter % 60 !== 0) return;
  1110. const ballPos = this.activeBall.worldPosition;
  1111. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) return;
  1112. let nearestDistance = Infinity;
  1113. let nearestBlock = null;
  1114. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  1115. const block = this.placedBlocksContainer.children[i];
  1116. if (block.name.includes('Block') || block.getChildByName('B1')) {
  1117. const blockPos = block.worldPosition;
  1118. const distance = Math.sqrt(
  1119. Math.pow(ballPos.x - blockPos.x, 2) +
  1120. Math.pow(ballPos.y - blockPos.y, 2)
  1121. );
  1122. if (distance < nearestDistance) {
  1123. nearestDistance = distance;
  1124. nearestBlock = block;
  1125. }
  1126. }
  1127. }
  1128. if (nearestBlock && nearestDistance < 100) {
  1129. // 检查小球的碰撞体状态
  1130. const ballCollider = this.activeBall.getComponent(Collider2D);
  1131. if (ballCollider) {
  1132. if (ballCollider instanceof CircleCollider2D) {
  1133. // 小球碰撞半径检查
  1134. }
  1135. }
  1136. // 检查小球的刚体状态
  1137. const ballRigidBody = this.activeBall.getComponent(RigidBody2D);
  1138. if (ballRigidBody) {
  1139. // 刚体状态检查
  1140. }
  1141. // 检查最近的方块碰撞体
  1142. const blockCollider = nearestBlock.getComponent(Collider2D);
  1143. if (blockCollider) {
  1144. // 方块碰撞体检查
  1145. }
  1146. }
  1147. }
  1148. // 初始化方向
  1149. initializeDirection() {
  1150. // 随机初始方向
  1151. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  1152. this.direction.x = Math.cos(angle);
  1153. this.direction.y = Math.sin(angle);
  1154. this.direction.normalize();
  1155. // 设置初始速度
  1156. if (this.activeBall) {
  1157. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  1158. if (rigidBody) {
  1159. rigidBody.linearVelocity = new Vec2(
  1160. this.direction.x * this.currentSpeed,
  1161. this.direction.y * this.currentSpeed
  1162. );
  1163. }
  1164. }
  1165. }
  1166. // 初始化球的参数 - 公开方法,供GameManager调用
  1167. public initialize() {
  1168. this.calculateGameBounds();
  1169. this.createBall();
  1170. // 检查方块碰撞体(延迟执行,确保方块已放置)
  1171. this.scheduleOnce(() => {
  1172. this.checkBlockColliders();
  1173. }, 0.5);
  1174. }
  1175. // 启动小球 - 公开方法,在确定按钮点击后调用
  1176. public startBall() {
  1177. // 检查ballPrefab是否设置
  1178. if (!this.ballPrefab) {
  1179. console.error('[BallController] ballPrefab 未设置,无法创建小球');
  1180. return;
  1181. }
  1182. // 如果还没有初始化,先初始化
  1183. if (!this.initialized) {
  1184. this.initialize();
  1185. }
  1186. // 确保小球存在且有效
  1187. if (!this.activeBall || !this.activeBall.isValid) {
  1188. this.createBall();
  1189. }
  1190. // 检查小球是否成功创建
  1191. if (!this.activeBall) {
  1192. console.error('[BallController] 小球创建失败');
  1193. return;
  1194. }
  1195. // 重新定位小球,避免与方块重叠
  1196. this.positionBallRandomly();
  1197. // 确保物理组件设置正确
  1198. this.setupCollider();
  1199. // 初始化运动方向并开始运动
  1200. this.initializeDirection();
  1201. // 设置运动状态
  1202. this.ballStarted = true;
  1203. console.log('[BallController] 小球启动完成');
  1204. }
  1205. /**
  1206. * 暂停小球运动:记录当前速度并停止刚体
  1207. */
  1208. public pauseBall() {
  1209. if (this.isPaused) return;
  1210. this.isPaused = true;
  1211. this.ballStarted = false;
  1212. if (this.activeBall && this.activeBall.isValid) {
  1213. const rb = this.activeBall.getComponent(RigidBody2D);
  1214. if (rb) {
  1215. this.pausedVelocity = rb.linearVelocity.clone();
  1216. rb.linearVelocity = new Vec2(0, 0);
  1217. rb.sleep();
  1218. }
  1219. }
  1220. }
  1221. /**
  1222. * 恢复小球运动:恢复暂停前的速度
  1223. */
  1224. public resumeBall() {
  1225. if (!this.isPaused) return;
  1226. this.isPaused = false;
  1227. this.ballStarted = true;
  1228. console.log('恢复小球运动');
  1229. if (this.activeBall && this.activeBall.isValid) {
  1230. const rb = this.activeBall.getComponent(RigidBody2D);
  1231. if (rb) {
  1232. rb.wakeUp();
  1233. const hasPrevVelocity = this.pausedVelocity && (this.pausedVelocity.x !== 0 || this.pausedVelocity.y !== 0);
  1234. if (hasPrevVelocity) {
  1235. rb.linearVelocity = this.pausedVelocity.clone();
  1236. } else {
  1237. // 若没有记录速度,则重新初始化方向
  1238. this.initializeDirection();
  1239. }
  1240. }
  1241. }
  1242. }
  1243. /**
  1244. * 从给定世界坐标发射子弹
  1245. */
  1246. private fireBulletAt(blockNode: Node, fireWorldPos: Vec3) {
  1247. // 检查子弹预制体是否存在
  1248. if (!this.bulletPrefab) {
  1249. return;
  1250. }
  1251. // 直接使用碰撞世界坐标作为发射点
  1252. const weaponConfig: WeaponConfig | null = (blockNode as any)['weaponConfig'] || null;
  1253. this.createAndFireBullet(fireWorldPos, weaponConfig);
  1254. }
  1255. /**
  1256. * 重置球控制器状态 - 游戏重置时调用
  1257. */
  1258. public resetBallController() {
  1259. console.log('[BallController] 重置球控制器状态');
  1260. // 停止球的运动
  1261. this.ballStarted = false;
  1262. this.isPaused = false;
  1263. // 清理暂停状态
  1264. this.pausedVelocity = new Vec2();
  1265. // 销毁当前活动的球
  1266. if (this.activeBall && this.activeBall.isValid) {
  1267. console.log('[BallController] 销毁当前活动的球');
  1268. this.activeBall.destroy();
  1269. }
  1270. this.activeBall = null;
  1271. // 重置初始化状态
  1272. this.initialized = false;
  1273. // 清理冷却时间
  1274. this.blockFireCooldown.clear();
  1275. // 清理防围困状态数据
  1276. this.ballHitHistory.clear();
  1277. this.ballPhaseThrough.clear();
  1278. this.ballDeflectionAttempts.clear();
  1279. // 重置球速
  1280. this.updateBallSpeed();
  1281. console.log('[BallController] 球控制器重置完成');
  1282. }
  1283. /**
  1284. * 清理过期的防围困状态
  1285. */
  1286. private cleanupExpiredAntiTrapStates() {
  1287. const currentTime = performance.now() / 1000;
  1288. // 清理过期的穿透状态
  1289. for (const [ballId, endTime] of this.ballPhaseThrough.entries()) {
  1290. if (currentTime >= endTime) {
  1291. this.ballPhaseThrough.delete(ballId);
  1292. }
  1293. }
  1294. // 检查并重置长时间未频繁撞击的球的偏移尝试次数
  1295. for (const [ballId, hitHistory] of this.ballHitHistory.entries()) {
  1296. // 如果撞击历史为空或最近一次撞击超过时间窗口的一半,重置偏移尝试次数
  1297. if (hitHistory.length === 0 ||
  1298. (hitHistory.length > 0 && currentTime - hitHistory[hitHistory.length - 1] > this.antiTrapTimeWindow / 2)) {
  1299. if (this.ballDeflectionAttempts.has(ballId)) {
  1300. this.ballDeflectionAttempts.set(ballId, 0);
  1301. }
  1302. }
  1303. }
  1304. }
  1305. /**
  1306. * 清理单个小球的防围困状态数据
  1307. * @param ballId 小球的唯一标识符
  1308. */
  1309. public cleanupBallAntiTrapState(ballId: string) {
  1310. this.ballHitHistory.delete(ballId);
  1311. this.ballPhaseThrough.delete(ballId);
  1312. this.ballDeflectionAttempts.delete(ballId);
  1313. console.log(`Cleaned up anti-trap state for ball ${ballId}`);
  1314. }
  1315. onDestroy() {
  1316. // 清理事件监听
  1317. const eventBus = EventBus.getInstance();
  1318. eventBus.off(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
  1319. eventBus.off(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  1320. eventBus.off(GameEvents.RESET_BALL_CONTROLLER, this.onResetBallControllerEvent, this);
  1321. // 清理防围困状态数据
  1322. this.ballHitHistory.clear();
  1323. this.ballPhaseThrough.clear();
  1324. }
  1325. private updateBallSpeed() {
  1326. const skillManager = PersistentSkillManager.getInstance();
  1327. if (skillManager) {
  1328. this.currentSpeed = skillManager.applyBallSpeedBonus(this.baseSpeed);
  1329. } else {
  1330. this.currentSpeed = this.baseSpeed;
  1331. }
  1332. }
  1333. }