Your First Flutter Flame Game

Mar 6 2024 · Dart 3, Flutter 3.10.1, Android Studio 2021.3.1 or higher, Visual Studo Code 1.7.4 or higher

Part 1: Getting Started With Flame

06. Challenge: Add Saucer Component

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 05. Enable Debug Mode in Components Next episode: 07. Learn About Effects

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 06. Challenge: Add Saucer Component

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.