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 2: Effects & User Input

10. Add Bullet 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: 09. Understand User Input Next episode: 11. Rotate the Spaceship

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.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Sometimes, instead of loading a sprite, it might be simpler to draw it in a canvas.

Demo

Bullet

Start by defining Bullet in the same way as the other components.

import 'package:flame/components.dart';

class Bullet extends PositionComponent {
}
static const double bulletWidth = 12;
static const double bulletHeight = 4;
static final Vector2 bulletSize = Vector2(bulletWidth, bulletHeight);
static const bulletRect = Rect.fromLTWH(
  0,
  0,
  bulletWidth,
  bulletHeight,
);
final Vector2 velocity = Vector2.zero();
double directionAngle;
Bullet({
  required this.directionAngle,
  super.position,
}) : super(size: Bullet.bulletSize);
@override
FutureOr<void> onLoad() {
  angle = directionAngle;

  return super.onLoad();
}
@override
void render(Canvas canvas) {
}
final _bulletPaint = Paint()
..style = PaintingStyle.fill
..color = const Color(0xFFFFFFFF);
canvas.drawRect(Bullet.bulletRect, _bulletPaint);
@override
void update(double dt) {
  velocity.x = GameConstants.bulletSpeed * cos(directionAngle);
  velocity.y = GameConstants.bulletSpeed * sin(directionAngle);
  position += velocity * dt;

  super.update(dt);
}
    if (position.x > GameConstants.cameraWidth || position.x < 0) {
      removeFromParent();
    }
    if (position.y > GameConstants.cameraHeight || position.y < 0) {
      removeFromParent();
    }

MeteormaniaGame

It’s time to add Bullet to the game world.

bool _isShooting = false;
Spaceship? _spaceship;
_spaceship = Spaceship()
  ..anchor = Anchor.center
  ..position = Vector2(
    GameConstants.cameraWidth / 2,
    GameConstants.cameraHeight / 2,
  );
_world.add(_spaceship!);
void shootBullet() {
}
if (!_isShooting && !manager.isGameOver) {
}
_isShooting = true;
_world.add(
  Bullet(directionAngle: _spaceship!.angle + 3 * pi / 2)
    ..anchor = Anchor.center
    ..position = _spaceship!.position,
);
_isShooting = false;
shootBullet();