BallController.ts 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608
  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. // 使用批量创建逻辑
  1000. const bullets = WeaponBullet.createBullets(initData, prefabToUse as any);
  1001. bullets.forEach(b => {
  1002. gameArea.addChild(b);
  1003. });
  1004. }).catch(error => {
  1005. // 武器配置加载失败
  1006. });
  1007. }
  1008. // 递归查找Weapon节点
  1009. private findWeaponNode(node: Node): Node | null {
  1010. // logs removed
  1011. // 先检查当前节点是否有Weapon子节点
  1012. const weaponNode = node.getChildByName('Weapon');
  1013. if (weaponNode) {
  1014. return weaponNode;
  1015. }
  1016. // 如果没有,递归检查所有子节点
  1017. for (let i = 0; i < node.children.length; i++) {
  1018. const child = node.children[i];
  1019. const foundWeapon = this.findWeaponNode(child);
  1020. if (foundWeapon) {
  1021. return foundWeapon;
  1022. }
  1023. }
  1024. // 如果都没找到,返回null
  1025. return null;
  1026. }
  1027. // 获取节点的完整路径
  1028. private getNodePath(node: Node): string {
  1029. let path = node.name;
  1030. let current = node;
  1031. while (current.parent) {
  1032. current = current.parent;
  1033. path = current.name + '/' + path;
  1034. }
  1035. return path;
  1036. }
  1037. update(dt: number) {
  1038. // 只有当小球已启动时才执行运动逻辑
  1039. if (!this.ballStarted || !this.initialized) {
  1040. return;
  1041. }
  1042. // 维持所有小球的恒定速度
  1043. this.maintainAllBallsSpeed();
  1044. // 清理过期的防围困状态
  1045. this.cleanupExpiredAntiTrapStates();
  1046. // 定期检查小球是否接近方块但没有触发碰撞(调试用)
  1047. if (this.activeBall && this.activeBall.isValid) {
  1048. this.debugCheckNearBlocks();
  1049. }
  1050. }
  1051. /**
  1052. * 维持所有小球的恒定速度
  1053. */
  1054. private maintainAllBallsSpeed() {
  1055. // 维持主小球速度
  1056. if (this.activeBall && this.activeBall.isValid) {
  1057. this.maintainBallSpeed(this.activeBall);
  1058. }
  1059. // 维持额外小球的速度
  1060. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1061. if (gameArea) {
  1062. const additionalBalls = gameArea.children.filter(child =>
  1063. child.name === 'AdditionalBall' && child.isValid
  1064. );
  1065. for (const ball of additionalBalls) {
  1066. this.maintainBallSpeed(ball);
  1067. }
  1068. }
  1069. }
  1070. /**
  1071. * 维持单个小球的恒定速度
  1072. */
  1073. private maintainBallSpeed(ball: Node) {
  1074. const rigidBody = ball.getComponent(RigidBody2D);
  1075. if (!rigidBody) return;
  1076. // 获取当前速度
  1077. const currentVelocity = rigidBody.linearVelocity;
  1078. const speed = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
  1079. // 如果速度过低或过高,重新设置速度以维持恒定运动
  1080. if (speed < this.currentSpeed * 0.85 || speed > this.currentSpeed * 1.15) {
  1081. // 保持当前方向,但调整速度大小
  1082. if (speed > 0.1) {
  1083. const normalizedVelocity = currentVelocity.clone().normalize();
  1084. rigidBody.linearVelocity = new Vec2(
  1085. normalizedVelocity.x * this.currentSpeed,
  1086. normalizedVelocity.y * this.currentSpeed
  1087. );
  1088. } else {
  1089. // 如果速度几乎为0,给一个随机方向
  1090. const angle = Math.random() * Math.PI * 2;
  1091. rigidBody.linearVelocity = new Vec2(
  1092. Math.cos(angle) * this.currentSpeed,
  1093. Math.sin(angle) * this.currentSpeed
  1094. );
  1095. }
  1096. }
  1097. // 更新主小球的方向向量(用于其他逻辑)
  1098. if (ball === this.activeBall && speed > 1.0) {
  1099. this.direction.x = currentVelocity.x / speed;
  1100. this.direction.y = currentVelocity.y / speed;
  1101. }
  1102. }
  1103. // 调试方法:检查小球是否接近方块但没有触发物理碰撞
  1104. private debugCheckCounter = 0;
  1105. private debugCheckNearBlocks() {
  1106. this.debugCheckCounter++;
  1107. // 每60帧(约1秒)检查一次
  1108. if (this.debugCheckCounter % 60 !== 0) return;
  1109. const ballPos = this.activeBall.worldPosition;
  1110. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) return;
  1111. let nearestDistance = Infinity;
  1112. let nearestBlock = null;
  1113. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  1114. const block = this.placedBlocksContainer.children[i];
  1115. if (block.name.includes('Block') || block.getChildByName('B1')) {
  1116. const blockPos = block.worldPosition;
  1117. const distance = Math.sqrt(
  1118. Math.pow(ballPos.x - blockPos.x, 2) +
  1119. Math.pow(ballPos.y - blockPos.y, 2)
  1120. );
  1121. if (distance < nearestDistance) {
  1122. nearestDistance = distance;
  1123. nearestBlock = block;
  1124. }
  1125. }
  1126. }
  1127. if (nearestBlock && nearestDistance < 100) {
  1128. // 检查小球的碰撞体状态
  1129. const ballCollider = this.activeBall.getComponent(Collider2D);
  1130. if (ballCollider) {
  1131. if (ballCollider instanceof CircleCollider2D) {
  1132. // 小球碰撞半径检查
  1133. }
  1134. }
  1135. // 检查小球的刚体状态
  1136. const ballRigidBody = this.activeBall.getComponent(RigidBody2D);
  1137. if (ballRigidBody) {
  1138. // 刚体状态检查
  1139. }
  1140. // 检查最近的方块碰撞体
  1141. const blockCollider = nearestBlock.getComponent(Collider2D);
  1142. if (blockCollider) {
  1143. // 方块碰撞体检查
  1144. }
  1145. }
  1146. }
  1147. // 初始化方向
  1148. initializeDirection() {
  1149. // 随机初始方向
  1150. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  1151. this.direction.x = Math.cos(angle);
  1152. this.direction.y = Math.sin(angle);
  1153. this.direction.normalize();
  1154. // 设置初始速度
  1155. if (this.activeBall) {
  1156. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  1157. if (rigidBody) {
  1158. rigidBody.linearVelocity = new Vec2(
  1159. this.direction.x * this.currentSpeed,
  1160. this.direction.y * this.currentSpeed
  1161. );
  1162. }
  1163. }
  1164. }
  1165. // 初始化球的参数 - 公开方法,供GameManager调用
  1166. public initialize() {
  1167. this.calculateGameBounds();
  1168. this.createBall();
  1169. // 检查方块碰撞体(延迟执行,确保方块已放置)
  1170. this.scheduleOnce(() => {
  1171. this.checkBlockColliders();
  1172. }, 0.5);
  1173. }
  1174. // 启动小球 - 公开方法,在确定按钮点击后调用
  1175. public startBall() {
  1176. // 检查ballPrefab是否设置
  1177. if (!this.ballPrefab) {
  1178. console.error('[BallController] ballPrefab 未设置,无法创建小球');
  1179. return;
  1180. }
  1181. // 如果还没有初始化,先初始化
  1182. if (!this.initialized) {
  1183. this.initialize();
  1184. }
  1185. // 确保小球存在且有效
  1186. if (!this.activeBall || !this.activeBall.isValid) {
  1187. this.createBall();
  1188. }
  1189. // 检查小球是否成功创建
  1190. if (!this.activeBall) {
  1191. console.error('[BallController] 小球创建失败');
  1192. return;
  1193. }
  1194. // 重新定位小球,避免与方块重叠
  1195. this.positionBallRandomly();
  1196. // 确保物理组件设置正确
  1197. this.setupCollider();
  1198. // 初始化运动方向并开始运动
  1199. this.initializeDirection();
  1200. // 设置运动状态
  1201. this.ballStarted = true;
  1202. console.log('[BallController] 小球启动完成');
  1203. }
  1204. /**
  1205. * 暂停小球运动:记录当前速度并停止刚体
  1206. */
  1207. public pauseBall() {
  1208. if (this.isPaused) return;
  1209. this.isPaused = true;
  1210. this.ballStarted = false;
  1211. if (this.activeBall && this.activeBall.isValid) {
  1212. const rb = this.activeBall.getComponent(RigidBody2D);
  1213. if (rb) {
  1214. this.pausedVelocity = rb.linearVelocity.clone();
  1215. rb.linearVelocity = new Vec2(0, 0);
  1216. rb.sleep();
  1217. }
  1218. }
  1219. }
  1220. /**
  1221. * 恢复小球运动:恢复暂停前的速度
  1222. */
  1223. public resumeBall() {
  1224. if (!this.isPaused) return;
  1225. this.isPaused = false;
  1226. this.ballStarted = true;
  1227. console.log('恢复小球运动');
  1228. if (this.activeBall && this.activeBall.isValid) {
  1229. const rb = this.activeBall.getComponent(RigidBody2D);
  1230. if (rb) {
  1231. rb.wakeUp();
  1232. const hasPrevVelocity = this.pausedVelocity && (this.pausedVelocity.x !== 0 || this.pausedVelocity.y !== 0);
  1233. if (hasPrevVelocity) {
  1234. rb.linearVelocity = this.pausedVelocity.clone();
  1235. } else {
  1236. // 若没有记录速度,则重新初始化方向
  1237. this.initializeDirection();
  1238. }
  1239. }
  1240. }
  1241. }
  1242. /**
  1243. * 从给定世界坐标发射子弹
  1244. */
  1245. private fireBulletAt(blockNode: Node, fireWorldPos: Vec3) {
  1246. // 检查子弹预制体是否存在
  1247. if (!this.bulletPrefab) {
  1248. return;
  1249. }
  1250. // 直接使用碰撞世界坐标作为发射点
  1251. const weaponConfig: WeaponConfig | null = (blockNode as any)['weaponConfig'] || null;
  1252. this.createAndFireBullet(fireWorldPos, weaponConfig);
  1253. }
  1254. /**
  1255. * 重置球控制器状态 - 游戏重置时调用
  1256. */
  1257. public resetBallController() {
  1258. console.log('[BallController] 重置球控制器状态');
  1259. // 停止球的运动
  1260. this.ballStarted = false;
  1261. this.isPaused = false;
  1262. // 清理暂停状态
  1263. this.pausedVelocity = new Vec2();
  1264. // 销毁当前活动的球
  1265. if (this.activeBall && this.activeBall.isValid) {
  1266. console.log('[BallController] 销毁当前活动的球');
  1267. this.activeBall.destroy();
  1268. }
  1269. this.activeBall = null;
  1270. // 销毁所有额外创建的球
  1271. const gameArea = find('Canvas/GameLevelUI/GameArea');
  1272. if (gameArea) {
  1273. const additionalBalls = gameArea.children.filter(child =>
  1274. child.name === 'AdditionalBall' && child.isValid
  1275. );
  1276. for (const ball of additionalBalls) {
  1277. console.log('[BallController] 销毁额外球:', ball.name);
  1278. ball.destroy();
  1279. }
  1280. if (additionalBalls.length > 0) {
  1281. console.log(`[BallController] 已清理 ${additionalBalls.length} 个额外球`);
  1282. }
  1283. }
  1284. // 重置初始化状态
  1285. this.initialized = false;
  1286. // 清理冷却时间
  1287. this.blockFireCooldown.clear();
  1288. // 清理防围困状态数据
  1289. this.ballHitHistory.clear();
  1290. this.ballPhaseThrough.clear();
  1291. this.ballDeflectionAttempts.clear();
  1292. // 重置球速
  1293. this.updateBallSpeed();
  1294. console.log('[BallController] 球控制器重置完成');
  1295. }
  1296. /**
  1297. * 清理过期的防围困状态
  1298. */
  1299. private cleanupExpiredAntiTrapStates() {
  1300. const currentTime = performance.now() / 1000;
  1301. // 清理过期的穿透状态
  1302. for (const [ballId, endTime] of this.ballPhaseThrough.entries()) {
  1303. if (currentTime >= endTime) {
  1304. this.ballPhaseThrough.delete(ballId);
  1305. }
  1306. }
  1307. // 检查并重置长时间未频繁撞击的球的偏移尝试次数
  1308. for (const [ballId, hitHistory] of this.ballHitHistory.entries()) {
  1309. // 如果撞击历史为空或最近一次撞击超过时间窗口的一半,重置偏移尝试次数
  1310. if (hitHistory.length === 0 ||
  1311. (hitHistory.length > 0 && currentTime - hitHistory[hitHistory.length - 1] > this.antiTrapTimeWindow / 2)) {
  1312. if (this.ballDeflectionAttempts.has(ballId)) {
  1313. this.ballDeflectionAttempts.set(ballId, 0);
  1314. }
  1315. }
  1316. }
  1317. }
  1318. /**
  1319. * 清理单个小球的防围困状态数据
  1320. * @param ballId 小球的唯一标识符
  1321. */
  1322. public cleanupBallAntiTrapState(ballId: string) {
  1323. this.ballHitHistory.delete(ballId);
  1324. this.ballPhaseThrough.delete(ballId);
  1325. this.ballDeflectionAttempts.delete(ballId);
  1326. console.log(`Cleaned up anti-trap state for ball ${ballId}`);
  1327. }
  1328. onDestroy() {
  1329. // 清理事件监听
  1330. const eventBus = EventBus.getInstance();
  1331. eventBus.off(GameEvents.GAME_PAUSE, this.onGamePauseEvent, this);
  1332. eventBus.off(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  1333. eventBus.off(GameEvents.RESET_BALL_CONTROLLER, this.onResetBallControllerEvent, this);
  1334. // 清理防围困状态数据
  1335. this.ballHitHistory.clear();
  1336. this.ballPhaseThrough.clear();
  1337. }
  1338. private updateBallSpeed() {
  1339. const skillManager = PersistentSkillManager.getInstance();
  1340. if (skillManager) {
  1341. this.currentSpeed = skillManager.applyBallSpeedBonus(this.baseSpeed);
  1342. } else {
  1343. this.currentSpeed = this.baseSpeed;
  1344. }
  1345. }
  1346. }