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 3: Collision Detection & Overlays

14. Understand Collision Between Components

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: 13. Play Sound Effects Next episode: 15. Attack Saucers

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.

Notes: 14. Understand Collision Between Components

Check out Flame’s documentation about collision detection.

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

Collision detection is the detection of collisions between objects in the virtual environment of a game.

Demo

MeteormaniaGame

To enable collision detection you just have to add HasCollisionDetection as a mixin to MeteormaniaGame. It’ll help the game keep track of the components that can collide.

HasCollisionDetection 
bool _hitByEnemy = false;
void spaceshipHit(bool isBigMeteorite) {
}
FlameAudio.play('sfx/explosion.mp3');
if (!_hitByEnemy) {
  _hitByEnemy = true;
  manager.playerHit();
}
_spaceship?.add(
  OpacityEffect.fadeOut(
    EffectController(
      alternate: true,
      duration: 0.1,
      repeatCount: 5,
    ),
  ),
);
..onComplete = () {
  _hitByEnemy = false;
},

Spaceship

Now, to enable collisions on Spaceship, you’ll need to add two different mixins: CollisionCallbacks that informs the component when it collides with other components; and HasGameRef which let’s your component access the parent MeteormaniaGame it belongs to.

with CollisionCallbacks, HasGameRef<MeteormaniaGame>
@override
FutureOr<void> onLoad() {
  add(RectangleHitbox());
  return super.onLoad();
}
@override
void onCollision(Set<Vector2> intersectionPoints, PositionComponent other) {
  super.onCollision(intersectionPoints, other);
}
if (other is Meteorite) {
  game.spaceshipHit(other.isBig);
}

Meteorite

The only thing left to do is adding a hitbox for Meteorite. Again, find onLoad and add a RectangleHitbox to the component. This allows it to collide with other components that have collision detection enabled.

add(RectangleHitbox());