feat: Adding spawnWhenLoaded flag on SpawnComponent (#3334)

Adds a new flag on `SpawnComponent` to spawn a component when it is
loaded, similar to how we have on `TimerComponent`.

Its default is set to false to avoid breaking the current behaviour.
This commit is contained in:
Erick
2024-10-10 09:33:14 -03:00
committed by GitHub
parent d2d4b372d8
commit 51a7e26b1a
2 changed files with 59 additions and 0 deletions

View File

@ -26,6 +26,7 @@ class SpawnComponent extends Component {
this.within = true,
this.selfPositioning = false,
this.autoStart = true,
this.spawnWhenLoaded = false,
Random? random,
super.key,
}) : assert(
@ -48,6 +49,7 @@ class SpawnComponent extends Component {
this.within = true,
this.selfPositioning = false,
this.autoStart = true,
this.spawnWhenLoaded = false,
Random? random,
super.key,
}) : assert(
@ -107,6 +109,9 @@ class SpawnComponent extends Component {
/// Whether the timer automatically starts or not.
final bool autoStart;
/// Whether the timer should start when the [SpawnComponent] is loaded.
final bool spawnWhenLoaded;
@override
FutureOr<void> onLoad() async {
if (area == null && !selfPositioning) {
@ -153,6 +158,7 @@ class SpawnComponent extends Component {
amount++;
},
autoStart: autoStart,
tickWhenLoaded: spawnWhenLoaded,
);
timer = timerComponent.timer;
add(timerComponent);

View File

@ -166,5 +166,58 @@ void main() {
await game.ready();
expect(world.children.length, 2);
});
testWithFlameGame(
'Does not spawns right away when spawnWhenLoaded is false (default)',
(game) async {
final random = Random(0);
final shape = Rectangle.fromCenter(
center: Vector2(100, 200),
size: Vector2.all(200),
);
final spawn = SpawnComponent(
factory: (_) => PositionComponent(),
period: 1,
area: shape,
random: random,
);
final world = game.world;
await world.ensureAdd(spawn);
expect(world.children.whereType<PositionComponent>(), isEmpty);
game.update(1.5);
await game.ready();
expect(
world.children.whereType<PositionComponent>(),
hasLength(1),
);
},
);
testWithFlameGame(
'Spawns right away when spawnWhenLoaded is true',
(game) async {
final random = Random(0);
final shape = Rectangle.fromCenter(
center: Vector2(100, 200),
size: Vector2.all(200),
);
final spawn = SpawnComponent(
factory: (_) => PositionComponent(),
period: 1,
area: shape,
random: random,
spawnWhenLoaded: true,
);
final world = game.world;
await world.ensureAdd(spawn);
expect(world.children.whereType<PositionComponent>(), hasLength(1));
game.update(1.5);
await game.ready();
expect(
world.children.whereType<PositionComponent>(),
hasLength(2),
);
},
);
});
}