BallController.ts 59 KB

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