BallController.ts 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665
  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. import { WeaponInfo } from './BlockSelection/WeaponInfo';
  10. const { ccclass, property } = _decorator;
  11. @ccclass('BallController')
  12. export class BallController extends Component {
  13. // 球的预制体
  14. @property({
  15. type: Prefab,
  16. tooltip: '拖拽Ball预制体到这里'
  17. })
  18. public ballPrefab: Prefab = null;
  19. // 已放置方块容器节点
  20. @property({
  21. type: Node,
  22. tooltip: '拖拽PlacedBlocks节点到这里(Canvas/GameLevelUI/PlacedBlocks)'
  23. })
  24. public placedBlocksContainer: Node = null;
  25. // 球控制器配置文件
  26. @property({
  27. type: JsonAsset,
  28. tooltip: '拖拽ballController.json配置文件到这里'
  29. })
  30. public ballControllerConfig: JsonAsset = null;
  31. // 球的移动速度(从配置文件加载)
  32. public baseSpeed: number = 60;
  33. public currentSpeed: number = 60;
  34. // 反弹随机偏移最大角度(弧度)(从配置文件加载)
  35. public maxReflectionRandomness: number = 0.2;
  36. // 当前活动的球
  37. private activeBall: Node = null;
  38. // 球的方向向量
  39. private direction: Vec2 = new Vec2();
  40. // GameArea区域边界
  41. private gameBounds = {
  42. left: 0,
  43. right: 0,
  44. top: 0,
  45. bottom: 0
  46. };
  47. // 球的半径
  48. private radius: number = 0;
  49. // 配置数据
  50. private config: BallControllerConfig = null;
  51. // 是否已初始化
  52. private initialized: boolean = false;
  53. // 子弹预制体
  54. @property({
  55. type: Prefab,
  56. tooltip: '拖拽子弹预制体到这里'
  57. })
  58. public bulletPrefab: Prefab = null;
  59. // 小球是否已开始运动
  60. private ballStarted: boolean = false;
  61. // 小球暂停时记录的速度
  62. private pausedVelocity: Vec2 = new Vec2();
  63. // 标记是否处于暂停状态
  64. private isPaused: boolean = false;
  65. // 在类字段区添加
  66. private blockFireCooldown: Map<string, number> = new Map();
  67. private FIRE_COOLDOWN = 0.05;
  68. // 防围困机制配置(从配置文件加载)
  69. public antiTrapTimeWindow: number = 5.0;
  70. public antiTrapHitThreshold: number = 5;
  71. public deflectionAttemptThreshold: number = 3;
  72. public antiTrapDeflectionMultiplier: number = 3.0;
  73. // 防围困机制状态
  74. private ballHitHistory: Map<string, number[]> = new Map(); // 记录每个球的撞击时间历史
  75. private ballPhaseThrough: Map<string, number> = new Map(); // 记录每个球的穿透结束时间
  76. private ballDeflectionAttempts: Map<string, number> = new Map(); // 记录每个球的偏移尝试次数
  77. // 带尾部特效的子弹容器预制体
  78. @property({
  79. type: Prefab,
  80. tooltip: '拖拽带尾部特效的子弹容器预制体到这里(例如 PelletContainer)'
  81. })
  82. public bulletContainerPrefab: Prefab = null;
  83. start() {
  84. // 如果没有指定placedBlocksContainer,尝试找到它
  85. if (!this.placedBlocksContainer) {
  86. this.placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks');
  87. if (!this.placedBlocksContainer) {
  88. // 找不到PlacedBlocks节点,某些功能可能无法正常工作
  89. }
  90. }
  91. // 加载配置
  92. this.loadConfig();
  93. // 只进行初始设置,不创建小球
  94. this.calculateGameBounds();
  95. // 监听游戏事件
  96. this.setupEventListeners();
  97. // 监听球速技能变化并更新球速
  98. this.updateBallSpeed();
  99. }
  100. /**
  101. * 设置事件监听器
  102. */
  103. // 加载配置
  104. private loadConfig() {
  105. if (this.ballControllerConfig && this.ballControllerConfig.json) {
  106. this.config = this.ballControllerConfig.json as BallControllerConfig;
  107. this.applyConfig();
  108. console.log('[BallController] ✅ 配置文件通过装饰器加载成功:', this.config);
  109. } else {
  110. console.warn('[BallController] ⚠️ 配置文件未设置,使用默认值');
  111. // 使用默认配置
  112. this.config = {
  113. baseSpeed: 60,
  114. maxReflectionRandomness: 0.2,
  115. antiTrapTimeWindow: 5.0,
  116. antiTrapHitThreshold: 5,
  117. deflectionAttemptThreshold: 3,
  118. antiTrapDeflectionMultiplier: 3.0,
  119. FIRE_COOLDOWN: 0.05,
  120. ballRadius: 10,
  121. gravityScale: 0,
  122. linearDamping: 0,
  123. angularDamping: 0,
  124. colliderGroup: 1,
  125. colliderTag: 1,
  126. friction: 0,
  127. restitution: 1,
  128. safeDistance: 50,
  129. edgeOffset: 20,
  130. sensor: false,
  131. maxAttempts: 50
  132. };
  133. this.applyConfig();
  134. }
  135. }
  136. // 应用配置
  137. private applyConfig() {
  138. if (!this.config) return;
  139. this.baseSpeed = this.config.baseSpeed;
  140. this.currentSpeed = this.config.baseSpeed;
  141. this.maxReflectionRandomness = this.config.maxReflectionRandomness;
  142. this.antiTrapTimeWindow = this.config.antiTrapTimeWindow;
  143. this.antiTrapHitThreshold = this.config.antiTrapHitThreshold;
  144. this.deflectionAttemptThreshold = this.config.deflectionAttemptThreshold;
  145. this.antiTrapDeflectionMultiplier = this.config.antiTrapDeflectionMultiplier;
  146. this.FIRE_COOLDOWN = this.config.FIRE_COOLDOWN;
  147. console.log('BallController配置已应用:', this.config);
  148. }
  149. // 从配置中获取参数值的辅助方法
  150. private getConfigValue<T>(key: keyof BallControllerConfig, defaultValue: T): T {
  151. return this.config && this.config[key] !== undefined ? this.config[key] as T : defaultValue;
  152. }
  153. // 配置参数的getter方法
  154. private get ballRadius(): number {
  155. return this.getConfigValue('ballRadius', 10);
  156. }
  157. private get gravityScale(): number {
  158. return this.getConfigValue('gravityScale', 0);
  159. }
  160. private get linearDamping(): number {
  161. return this.getConfigValue('linearDamping', 0);
  162. }
  163. private get angularDamping(): number {
  164. return this.getConfigValue('angularDamping', 0);
  165. }
  166. private get colliderGroup(): number {
  167. return this.getConfigValue('colliderGroup', 2);
  168. }
  169. private get colliderTag(): number {
  170. return this.getConfigValue('colliderTag', 1);
  171. }
  172. private get friction(): number {
  173. return this.getConfigValue('friction', 0);
  174. }
  175. private get restitution(): number {
  176. return this.getConfigValue('restitution', 1);
  177. }
  178. private get safeDistance(): number {
  179. return this.getConfigValue('safeDistance', 50);
  180. }
  181. private get edgeOffset(): number {
  182. return this.getConfigValue('edgeOffset', 20);
  183. }
  184. private get sensor(): boolean {
  185. return this.getConfigValue('sensor', false);
  186. }
  187. private get maxAttempts(): number {
  188. return this.getConfigValue('maxAttempts', 50);
  189. }
  190. private setupEventListeners() {
  191. const eventBus = EventBus.getInstance();
  192. // 监听暂停事件
  193. eventBus.on(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
  194. // 监听恢复事件
  195. eventBus.on(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  196. // 监听重置球控制器事件
  197. eventBus.on(GameEvents.RESET_BALL_CONTROLLER, this.onResetBallControllerEvent, this);
  198. // 监听球创建事件
  199. eventBus.on(GameEvents.BALL_CREATE, this.onBallCreateEvent, this);
  200. // 监听球启动事件
  201. eventBus.on(GameEvents.BALL_START, this.onBallStartEvent, this);
  202. // 监听创建额外球事件
  203. eventBus.on(GameEvents.BALL_CREATE_ADDITIONAL, this.onBallCreateAdditionalEvent, this);
  204. // 监听子弹发射检查事件
  205. eventBus.on(GameEvents.BALL_FIRE_BULLET, this.onBallFireBulletEvent, this);
  206. }
  207. /**
  208. * 处理游戏暂停事件
  209. */
  210. private onGamePauseEvent() {
  211. console.log('[BallController] 接收到游戏暂停事件,暂停小球运动');
  212. this.pauseBall();
  213. }
  214. /**
  215. * 处理游戏恢复事件
  216. */
  217. private onGameResumeEvent() {
  218. console.log('[BallController] 接收到游戏恢复事件,恢复小球运动');
  219. this.resumeBall();
  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. /**
  250. * 处理子弹发射检查事件
  251. */
  252. private onBallFireBulletEvent(blockNode: Node, fireWorldPos: Vec3) {
  253. // 如果游戏暂停,则不允许发射子弹
  254. if (this.isPaused) {
  255. console.log('[BallController] 游戏暂停中,阻止子弹发射');
  256. return;
  257. }
  258. // 如果游戏未暂停,则继续执行子弹发射逻辑
  259. this.fireBulletAt(blockNode, fireWorldPos);
  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 weaponNode 武器节点(包含WeaponInfo组件)
  960. */
  961. private createAndFireBullet(firePosition: Vec3, weaponNode: Node | null) {
  962. // 确保武器配置加载
  963. WeaponBullet.loadWeaponsData().then(() => {
  964. let finalConfig: WeaponConfig | null = null;
  965. // 优先从武器节点的WeaponInfo组件获取配置
  966. if (weaponNode && weaponNode.isValid) {
  967. const weaponInfo = weaponNode.getComponent(WeaponInfo);
  968. if (weaponInfo) {
  969. finalConfig = weaponInfo.getWeaponConfig();
  970. console.log(`[BallController] 从武器节点获取武器配置: ${finalConfig?.name || '未知'}`);
  971. // 检查武器是否可以开火
  972. if (!weaponInfo.canFire()) {
  973. console.log(`[BallController] 武器 ${finalConfig?.name || '未知'} 冷却中,无法开火`);
  974. return;
  975. }
  976. // 记录开火时间
  977. weaponInfo.recordFireTime();
  978. }
  979. }
  980. // 如果没有从武器节点获取到配置,使用默认配置
  981. if (!finalConfig) {
  982. const defaultWeaponId = 'pea_shooter';
  983. finalConfig = WeaponBullet.getWeaponConfig(defaultWeaponId);
  984. console.log(`[BallController] 使用默认武器配置: ${defaultWeaponId}`);
  985. }
  986. if (!finalConfig) {
  987. console.warn(`[BallController] 无法获取武器配置,取消发射`);
  988. return;
  989. }
  990. // 获取WeaponInfo组件(如果有的话)
  991. let weaponInfoComponent: WeaponInfo | null = null;
  992. if (weaponNode && weaponNode.isValid) {
  993. weaponInfoComponent = weaponNode.getComponent(WeaponInfo);
  994. }
  995. // 创建子弹初始化数据
  996. const initData: BulletInitData = {
  997. weaponId: finalConfig.id,
  998. firePosition: firePosition,
  999. autoTarget: true,
  1000. weaponConfig: finalConfig,
  1001. weaponInfo: weaponInfoComponent
  1002. };
  1003. // 验证初始化数据
  1004. if (!WeaponBullet.validateInitData(initData)) {
  1005. console.warn(`[BallController] 子弹初始化数据验证失败`);
  1006. return;
  1007. }
  1008. // 查找GameArea(子弹统一添加到此节点)
  1009. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1010. if (!gameArea) {
  1011. console.warn(`[BallController] 未找到GameArea节点,无法发射子弹`);
  1012. return;
  1013. }
  1014. // === 根据武器配置选择合适的预制体 ===
  1015. const trailEffect = finalConfig.bulletConfig?.visual?.trailEffect;
  1016. // 尖胡萝卜特殊处理:使用PelletContainer预制体但激活Spine节点
  1017. const isSharpCarrot = finalConfig.id === 'sharp_carrot';
  1018. // 当trailEffect为true或者是尖胡萝卜时都使用容器预制体
  1019. const needsContainerPrefab = Boolean(trailEffect) || isSharpCarrot;
  1020. const prefabToUse: Prefab = (needsContainerPrefab && this.bulletContainerPrefab) ? this.bulletContainerPrefab : this.bulletPrefab;
  1021. if (!prefabToUse) {
  1022. console.warn(`[BallController] 没有可用的子弹预制体`);
  1023. return;
  1024. }
  1025. // 使用批量创建逻辑
  1026. console.log(`[BallController] 开始创建子弹 - 武器: ${finalConfig.name}, 预制体: ${prefabToUse ? prefabToUse.name : 'null'}`);
  1027. const bullets = WeaponBullet.createBullets(initData, prefabToUse as any);
  1028. console.log(`[BallController] WeaponBullet.createBullets 返回了 ${bullets.length} 个子弹`);
  1029. bullets.forEach((b, index) => {
  1030. console.log(`[BallController] 添加第 ${index + 1} 个子弹到场景 - 子弹节点: ${b ? b.name : 'null'}, 是否有效: ${b ? b.isValid : 'false'}`);
  1031. if (b && b.isValid) {
  1032. gameArea.addChild(b);
  1033. console.log(`[BallController] 子弹 ${index + 1} 成功添加到场景,世界坐标: ${b.worldPosition}`);
  1034. } else {
  1035. console.error(`[BallController] 子弹 ${index + 1} 无效,无法添加到场景`);
  1036. }
  1037. });
  1038. console.log(`[BallController] 成功发射 ${bullets.length} 发子弹,武器: ${finalConfig.name}`);
  1039. }).catch(error => {
  1040. console.error(`[BallController] 武器配置加载失败:`, error);
  1041. });
  1042. }
  1043. // 递归查找Weapon节点
  1044. private findWeaponNode(node: Node): Node | null {
  1045. // 检查节点是否有效
  1046. if (!node || !node.isValid) {
  1047. console.warn('[BallController] findWeaponNode: 传入的节点无效');
  1048. return null;
  1049. }
  1050. // 先检查当前节点是否有Weapon子节点
  1051. const weaponNode = node.getChildByName('Weapon');
  1052. if (weaponNode) {
  1053. return weaponNode;
  1054. }
  1055. // 如果没有,递归检查所有子节点
  1056. for (let i = 0; i < node.children.length; i++) {
  1057. const child = node.children[i];
  1058. const foundWeapon = this.findWeaponNode(child);
  1059. if (foundWeapon) {
  1060. return foundWeapon;
  1061. }
  1062. }
  1063. // 如果都没找到,返回null
  1064. return null;
  1065. }
  1066. // 获取节点的完整路径
  1067. private getNodePath(node: Node): string {
  1068. let path = node.name;
  1069. let current = node;
  1070. while (current.parent) {
  1071. current = current.parent;
  1072. path = current.name + '/' + path;
  1073. }
  1074. return path;
  1075. }
  1076. update(dt: number) {
  1077. // 只有当小球已启动时才执行运动逻辑
  1078. if (!this.ballStarted || !this.initialized) {
  1079. return;
  1080. }
  1081. // 维持所有小球的恒定速度
  1082. this.maintainAllBallsSpeed();
  1083. // 清理过期的防围困状态
  1084. this.cleanupExpiredAntiTrapStates();
  1085. // 定期检查小球是否接近方块但没有触发碰撞(调试用)
  1086. if (this.activeBall && this.activeBall.isValid) {
  1087. this.debugCheckNearBlocks();
  1088. }
  1089. }
  1090. /**
  1091. * 维持所有小球的恒定速度
  1092. */
  1093. private maintainAllBallsSpeed() {
  1094. // 维持主小球速度
  1095. if (this.activeBall && this.activeBall.isValid) {
  1096. this.maintainBallSpeed(this.activeBall);
  1097. }
  1098. // 维持额外小球的速度
  1099. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1100. if (gameArea) {
  1101. const additionalBalls = gameArea.children.filter(child =>
  1102. child.name === 'AdditionalBall' && child.isValid
  1103. );
  1104. for (const ball of additionalBalls) {
  1105. this.maintainBallSpeed(ball);
  1106. }
  1107. }
  1108. }
  1109. /**
  1110. * 维持单个小球的恒定速度
  1111. */
  1112. private maintainBallSpeed(ball: Node) {
  1113. const rigidBody = ball.getComponent(RigidBody2D);
  1114. if (!rigidBody) return;
  1115. // 获取当前速度
  1116. const currentVelocity = rigidBody.linearVelocity;
  1117. const speed = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
  1118. // 如果速度过低或过高,重新设置速度以维持恒定运动
  1119. if (speed < this.currentSpeed * 0.85 || speed > this.currentSpeed * 1.15) {
  1120. // 保持当前方向,但调整速度大小
  1121. if (speed > 0.1) {
  1122. const normalizedVelocity = currentVelocity.clone().normalize();
  1123. rigidBody.linearVelocity = new Vec2(
  1124. normalizedVelocity.x * this.currentSpeed,
  1125. normalizedVelocity.y * this.currentSpeed
  1126. );
  1127. } else {
  1128. // 如果速度几乎为0,给一个随机方向
  1129. const angle = Math.random() * Math.PI * 2;
  1130. rigidBody.linearVelocity = new Vec2(
  1131. Math.cos(angle) * this.currentSpeed,
  1132. Math.sin(angle) * this.currentSpeed
  1133. );
  1134. }
  1135. }
  1136. // 更新主小球的方向向量(用于其他逻辑)
  1137. if (ball === this.activeBall && speed > 1.0) {
  1138. this.direction.x = currentVelocity.x / speed;
  1139. this.direction.y = currentVelocity.y / speed;
  1140. }
  1141. }
  1142. // 调试方法:检查小球是否接近方块但没有触发物理碰撞
  1143. private debugCheckCounter = 0;
  1144. private debugCheckNearBlocks() {
  1145. this.debugCheckCounter++;
  1146. // 每60帧(约1秒)检查一次
  1147. if (this.debugCheckCounter % 60 !== 0) return;
  1148. const ballPos = this.activeBall.worldPosition;
  1149. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) return;
  1150. let nearestDistance = Infinity;
  1151. let nearestBlock = null;
  1152. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  1153. const block = this.placedBlocksContainer.children[i];
  1154. if (block.name.includes('Block') || block.getChildByName('B1')) {
  1155. const blockPos = block.worldPosition;
  1156. const distance = Math.sqrt(
  1157. Math.pow(ballPos.x - blockPos.x, 2) +
  1158. Math.pow(ballPos.y - blockPos.y, 2)
  1159. );
  1160. if (distance < nearestDistance) {
  1161. nearestDistance = distance;
  1162. nearestBlock = block;
  1163. }
  1164. }
  1165. }
  1166. if (nearestBlock && nearestDistance < 100) {
  1167. // 检查小球的碰撞体状态
  1168. const ballCollider = this.activeBall.getComponent(Collider2D);
  1169. if (ballCollider) {
  1170. if (ballCollider instanceof CircleCollider2D) {
  1171. // 小球碰撞半径检查
  1172. }
  1173. }
  1174. // 检查小球的刚体状态
  1175. const ballRigidBody = this.activeBall.getComponent(RigidBody2D);
  1176. if (ballRigidBody) {
  1177. // 刚体状态检查
  1178. }
  1179. // 检查最近的方块碰撞体
  1180. const blockCollider = nearestBlock.getComponent(Collider2D);
  1181. if (blockCollider) {
  1182. // 方块碰撞体检查
  1183. }
  1184. }
  1185. }
  1186. // 初始化方向
  1187. initializeDirection() {
  1188. // 随机初始方向
  1189. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  1190. this.direction.x = Math.cos(angle);
  1191. this.direction.y = Math.sin(angle);
  1192. this.direction.normalize();
  1193. // 设置初始速度
  1194. if (this.activeBall) {
  1195. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  1196. if (rigidBody) {
  1197. rigidBody.linearVelocity = new Vec2(
  1198. this.direction.x * this.currentSpeed,
  1199. this.direction.y * this.currentSpeed
  1200. );
  1201. }
  1202. }
  1203. }
  1204. // 初始化球的参数 - 公开方法,供GameManager调用
  1205. public initialize() {
  1206. this.calculateGameBounds();
  1207. this.createBall();
  1208. // 检查方块碰撞体(延迟执行,确保方块已放置)
  1209. this.scheduleOnce(() => {
  1210. this.checkBlockColliders();
  1211. }, 0.5);
  1212. }
  1213. // 启动小球 - 公开方法,在确定按钮点击后调用
  1214. public startBall() {
  1215. // 检查ballPrefab是否设置
  1216. if (!this.ballPrefab) {
  1217. console.error('[BallController] ballPrefab 未设置,无法创建小球');
  1218. return;
  1219. }
  1220. // 如果还没有初始化,先初始化
  1221. if (!this.initialized) {
  1222. this.initialize();
  1223. }
  1224. // 确保小球存在且有效
  1225. if (!this.activeBall || !this.activeBall.isValid) {
  1226. this.createBall();
  1227. }
  1228. // 检查小球是否成功创建
  1229. if (!this.activeBall) {
  1230. console.error('[BallController] 小球创建失败');
  1231. return;
  1232. }
  1233. // 重新定位小球,避免与方块重叠
  1234. this.positionBallRandomly();
  1235. // 确保物理组件设置正确
  1236. this.setupCollider();
  1237. // 初始化运动方向并开始运动
  1238. this.initializeDirection();
  1239. // 设置运动状态
  1240. this.ballStarted = true;
  1241. console.log('[BallController] 小球启动完成');
  1242. }
  1243. /**
  1244. * 暂停小球运动:记录当前速度并停止刚体
  1245. */
  1246. public pauseBall() {
  1247. if (this.isPaused) return;
  1248. this.isPaused = true;
  1249. this.ballStarted = false;
  1250. if (this.activeBall && this.activeBall.isValid) {
  1251. const rb = this.activeBall.getComponent(RigidBody2D);
  1252. if (rb) {
  1253. this.pausedVelocity = rb.linearVelocity.clone();
  1254. rb.linearVelocity = new Vec2(0, 0);
  1255. rb.sleep();
  1256. }
  1257. }
  1258. }
  1259. /**
  1260. * 恢复小球运动:恢复暂停前的速度
  1261. */
  1262. public resumeBall() {
  1263. if (!this.isPaused) return;
  1264. this.isPaused = false;
  1265. this.ballStarted = true;
  1266. console.log('恢复小球运动');
  1267. if (this.activeBall && this.activeBall.isValid) {
  1268. const rb = this.activeBall.getComponent(RigidBody2D);
  1269. if (rb) {
  1270. rb.wakeUp();
  1271. const hasPrevVelocity = this.pausedVelocity && (this.pausedVelocity.x !== 0 || this.pausedVelocity.y !== 0);
  1272. if (hasPrevVelocity) {
  1273. rb.linearVelocity = this.pausedVelocity.clone();
  1274. } else {
  1275. // 若没有记录速度,则重新初始化方向
  1276. this.initializeDirection();
  1277. }
  1278. }
  1279. }
  1280. }
  1281. /**
  1282. * 从给定世界坐标发射子弹
  1283. */
  1284. private fireBulletAt(blockNode: Node, fireWorldPos: Vec3) {
  1285. // 检查方块节点是否有效
  1286. if (!blockNode || !blockNode.isValid) {
  1287. console.warn('[BallController] fireBulletAt: 方块节点无效,无法发射子弹');
  1288. return;
  1289. }
  1290. // 检查子弹预制体是否存在
  1291. if (!this.bulletPrefab) {
  1292. console.warn(`[BallController] 子弹预制体未设置,无法发射`);
  1293. return;
  1294. }
  1295. // 查找方块中的武器节点
  1296. const weaponNode = this.findWeaponNode(blockNode);
  1297. if (!weaponNode) {
  1298. const blockName = blockNode && blockNode.isValid ? blockNode.name : 'unknown';
  1299. console.warn(`[BallController] 方块 ${blockName} 中未找到武器节点`);
  1300. }
  1301. // 传递武器节点给createAndFireBullet方法
  1302. this.createAndFireBullet(fireWorldPos, weaponNode);
  1303. }
  1304. /**
  1305. * 重置球控制器状态 - 游戏重置时调用
  1306. */
  1307. public resetBallController() {
  1308. console.log('[BallController] 重置球控制器状态');
  1309. // 停止球的运动
  1310. this.ballStarted = false;
  1311. this.isPaused = false;
  1312. // 清理暂停状态
  1313. this.pausedVelocity = new Vec2();
  1314. // 销毁当前活动的球
  1315. if (this.activeBall && this.activeBall.isValid) {
  1316. console.log('[BallController] 销毁当前活动的球');
  1317. this.activeBall.destroy();
  1318. }
  1319. this.activeBall = null;
  1320. // 销毁所有额外创建的球
  1321. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1322. if (gameArea) {
  1323. const additionalBalls = gameArea.children.filter(child =>
  1324. child.name === 'AdditionalBall' && child.isValid
  1325. );
  1326. for (const ball of additionalBalls) {
  1327. console.log('[BallController] 销毁额外球:', ball.name);
  1328. ball.destroy();
  1329. }
  1330. if (additionalBalls.length > 0) {
  1331. console.log(`[BallController] 已清理 ${additionalBalls.length} 个额外球`);
  1332. }
  1333. }
  1334. // 重置初始化状态
  1335. this.initialized = false;
  1336. // 清理冷却时间
  1337. this.blockFireCooldown.clear();
  1338. // 清理防围困状态数据
  1339. this.ballHitHistory.clear();
  1340. this.ballPhaseThrough.clear();
  1341. this.ballDeflectionAttempts.clear();
  1342. // 重置球速
  1343. this.updateBallSpeed();
  1344. console.log('[BallController] 球控制器重置完成');
  1345. }
  1346. /**
  1347. * 清理过期的防围困状态
  1348. */
  1349. private cleanupExpiredAntiTrapStates() {
  1350. const currentTime = performance.now() / 1000;
  1351. // 清理过期的穿透状态
  1352. for (const [ballId, endTime] of this.ballPhaseThrough.entries()) {
  1353. if (currentTime >= endTime) {
  1354. this.ballPhaseThrough.delete(ballId);
  1355. }
  1356. }
  1357. // 检查并重置长时间未频繁撞击的球的偏移尝试次数
  1358. for (const [ballId, hitHistory] of this.ballHitHistory.entries()) {
  1359. // 如果撞击历史为空或最近一次撞击超过时间窗口的一半,重置偏移尝试次数
  1360. if (hitHistory.length === 0 ||
  1361. (hitHistory.length > 0 && currentTime - hitHistory[hitHistory.length - 1] > this.antiTrapTimeWindow / 2)) {
  1362. if (this.ballDeflectionAttempts.has(ballId)) {
  1363. this.ballDeflectionAttempts.set(ballId, 0);
  1364. }
  1365. }
  1366. }
  1367. }
  1368. /**
  1369. * 清理单个小球的防围困状态数据
  1370. * @param ballId 小球的唯一标识符
  1371. */
  1372. public cleanupBallAntiTrapState(ballId: string) {
  1373. this.ballHitHistory.delete(ballId);
  1374. this.ballPhaseThrough.delete(ballId);
  1375. this.ballDeflectionAttempts.delete(ballId);
  1376. console.log(`Cleaned up anti-trap state for ball ${ballId}`);
  1377. }
  1378. onDestroy() {
  1379. // 清理事件监听
  1380. const eventBus = EventBus.getInstance();
  1381. eventBus.off(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
  1382. eventBus.off(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  1383. eventBus.off(GameEvents.RESET_BALL_CONTROLLER, this.onResetBallControllerEvent, this);
  1384. // 清理防围困状态数据
  1385. this.ballHitHistory.clear();
  1386. this.ballPhaseThrough.clear();
  1387. }
  1388. private updateBallSpeed() {
  1389. const skillManager = PersistentSkillManager.getInstance();
  1390. if (skillManager) {
  1391. this.currentSpeed = skillManager.applyBallSpeedBonus(this.baseSpeed);
  1392. } else {
  1393. this.currentSpeed = this.baseSpeed;
  1394. }
  1395. }
  1396. }