Els components tenen definida una àrea de detacció al seu voltant que ens permet detectar quan entren en contacte. Per poder detectar les col·lisions, cal afegir-ne la detecció a la classe del joc.
class Breakout extends FlameGame with HasCollisionDetection {
Breakout()
...
Les àrees de detecció poden ser de formes diverses, les més habituals són RectangleHitbox i CircleHitbox. Cal afegir-les com a descendents en els components dels quals vulguem detectar les col·lisions.
Per exemple, per activar les col·lisions en una àrea de joc:
import 'package:flame/collisions.dart'; ...
class PlayArea extends RectangleComponent with HasGameReference{ PlayArea() : super( paint: Paint() ..color = const Color(0xfff2e8cf), children: [RectangleHitbox()], ); ...
I en un element del joc:
import 'package:flame/collisions.dart'; ...
class Bola extends CircleComponent
with CollisionCallbacks, HasGameReference {
Bola({
required this.velocity,
required super.position, // El paràmetre accedirà directament a l'original
required double radius,
}) : super(
radius: radius,
anchor: Anchor.center,
paint: Paint()
..color = const Color(0xff1e6091)
..style = PaintingStyle.fill,
children: [CircleHitbox()],
);
...
A més, cal implementar les corresponents accions en els elements on la col·lisió té algun efecte. Això ho fem sobrescrivint el mètode onCollisionStart (o bé onCollision o onCollisionEnd, segons correspongui).
...
@override
void onCollisionStart(
Set<Vector2> intersectionPoints,
PositionComponent other,
) {
super.onCollisionStart(intersectionPoints, other);
if (other is PlayArea) {
if (intersectionPoints.first.y <= 0) {
velocity.y = -velocity.y;
} else if (intersectionPoints.first.x <= 0) {
velocity.x = -velocity.x;
} else if (intersectionPoints.first.x >= game.width) {
velocity.x = -velocity.x;
} else if (intersectionPoints.first.y >= game.height) {
removeFromParent();
}
}
}
...

Aquesta obra d'Oriol Boix està llicenciada sota una llicència no importada Reconeixement-NoComercial-SenseObraDerivada 3.0.