You’ll use what you’ve learned during this course so far to define and add a new component called Saucer. It will be positioned randomly in the game’s screen like Meteorite.
Create a new SpriteComponent called Saucer and load the appropriate sprite from the preloaded spritesheet that you added for Meteorite.
Then, add your new component to your game world.
Remember to place it randomly in the screen in the same way you did for meteorites.
Pause the video and try the challenge… Then keep watching for the solution.
Hint: here’s the sprite’s width, height and position within the spritesheet:
width -> 128.0 height -> 64.0 x position -> 0 y position -> 0
Solution
Saucer
Open lib/components/saucer.dart. Define a class that extends SpriteComponent.
import 'package:flame/components.dart';
class Saucer extends SpriteComponent {
}
Then add the definitions for width, height, size and load the sprite.
static const double saucerWidth = 128.0;
static const double saucerHeight = 64.0;
static final Sprite saucerSprite = loadMeteormaniaSprite(0, 0, 128, 64);
static final Vector2 saucerSize = Vector2(saucerWidth, saucerHeight);
Finally, create a new constructor calling super to load the sprite.
Saucer() : super(sprite: saucerSprite, size: saucerSize);
MeteormaniaGame
Now let’s add it to _world. Back in MeteormaniaGame, in addEnemies function, create a new Saucer.
final (saucerX, saucerY) = randomPosition(
Saucer.saucerWidth * GameConstants.saucerMaxMovementFactor,
Saucer.saucerHeight * GameConstants.saucerMaxMovementFactor,
Spaceship.spaceshipSize.toSize(),
);
final saucer = Saucer()
..anchor = Anchor.center
..position = Vector2(saucerX, saucerY);
And, let’s add it to _world
_world
..add(saucer)
..addAll(meteorites);
Build and run the game again. Nice, you now have all the enemies in screen. Next, you will learn about game effects that you can use in your game using Flame.