bubble_spawner.dart 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import 'dart:math';
  2. import 'package:flame/components.dart';
  3. import 'bubble.dart';
  4. class BubbleSpawner extends Component with HasGameReference {
  5. static const double spawnInterval = 2.0; // seconds
  6. static const int maxBubbles = 8;
  7. double _timeSinceLastSpawn = 0;
  8. final List<Bubble> _activeBubbles = [];
  9. final Random _random = Random();
  10. Function(Bubble)? onBubblePopped;
  11. bool isActive = true;
  12. BubbleSpawner({this.onBubblePopped});
  13. @override
  14. void update(double dt) {
  15. super.update(dt);
  16. if (!isActive) return;
  17. _timeSinceLastSpawn += dt;
  18. // Spawn new bubble if conditions are met
  19. if (_timeSinceLastSpawn >= spawnInterval && _activeBubbles.length < maxBubbles) {
  20. _spawnBubble();
  21. _timeSinceLastSpawn = 0;
  22. }
  23. // Clean up popped bubbles
  24. _activeBubbles.removeWhere((bubble) => !bubble.isMounted);
  25. }
  26. void _spawnBubble() {
  27. if (game.size.x == 0 || game.size.y == 0) return;
  28. // Calculate safe spawn area (avoiding edges and UI elements)
  29. const margin = 80.0;
  30. final minX = margin;
  31. final maxX = game.size.x - margin;
  32. final minY = margin + 100; // Extra margin for score display
  33. final maxY = game.size.y - margin;
  34. if (maxX <= minX || maxY <= minY) return;
  35. final spawnPosition = Vector2(
  36. minX + _random.nextDouble() * (maxX - minX),
  37. minY + _random.nextDouble() * (maxY - minY),
  38. );
  39. final bubble = Bubble(
  40. position: spawnPosition,
  41. onPop: _onBubblePopped,
  42. );
  43. _activeBubbles.add(bubble);
  44. game.add(bubble);
  45. }
  46. void _onBubblePopped(Bubble bubble) {
  47. _activeBubbles.remove(bubble);
  48. onBubblePopped?.call(bubble);
  49. }
  50. void spawnBubbleAt(Vector2 position) {
  51. final bubble = Bubble(
  52. position: position,
  53. onPop: _onBubblePopped,
  54. );
  55. _activeBubbles.add(bubble);
  56. game.add(bubble);
  57. }
  58. void clearAllBubbles() {
  59. for (final bubble in _activeBubbles) {
  60. if (bubble.isMounted) {
  61. bubble.removeFromParent();
  62. }
  63. }
  64. _activeBubbles.clear();
  65. }
  66. void setActive(bool active) {
  67. isActive = active;
  68. }
  69. int get activeBubbleCount => _activeBubbles.length;
  70. }