refactor: ball with mixin Layer for mask collisions

pull/40/head
RuiAlonso 4 years ago
parent c880884b5c
commit 18d7df21a1

@ -6,7 +6,7 @@ import 'package:pinball/game/game.dart';
/// A solid, [BodyType.dynamic] sphere that rolls and bounces along the
/// [PinballGame].
/// {@endtemplate}
class Ball extends BodyComponent<PinballGame> {
class Ball extends BodyComponent<PinballGame> with Layer {
/// {@macro ball}
Ball({
required Vector2 position,
@ -44,17 +44,16 @@ class Ball extends BodyComponent<PinballGame> {
Body createBody() {
final shape = CircleShape()..radius = size.x / 2;
final fixtureDef = FixtureDef(shape)..density = 1;
final fixtureDef = FixtureDef(shape)
..density = 1
..filter.maskBits = _maskBits;
final bodyDef = BodyDef()
..userData = this
..position = Vector2(_position.x, _position.y + size.y)
..type = BodyType.dynamic;
final body = world.createBody(bodyDef);
body.createFixture(fixtureDef).filterData.maskBits = _maskBits;
return body;
return world.createBody(bodyDef)..createFixture(fixtureDef);
}
/// Removes the [Ball] from a [PinballGame]; spawning a new [Ball] if
@ -72,14 +71,4 @@ class Ball extends BodyComponent<PinballGame> {
gameRef.spawnBall();
}
}
/// Modifies maskBits of [Ball] for collisions.
///
/// Changes the [Filter] data for category and maskBits of the [Ball] to
/// collide with other objects of same bits and ignore others.
void setMaskBits(int maskBits) {
body.fixtures.first
..filterData.categoryBits = maskBits
..filterData.maskBits = maskBits;
}
}

@ -3,6 +3,23 @@
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball/game/game.dart';
/// {@template layer}
/// Modifies maskBits of [BodyComponent] for collisions.
///
/// Changes the [Filter] data for category and maskBits of
/// the [BodyComponent] to collide with other objects of
/// same bits and ignore others.
/// {@endtemplate}
mixin Layer on BodyComponent<PinballGame> {
void setMaskBits(int maskBits) {
body.fixtures.forEach(
(fixture) => fixture
..filterData.categoryBits = maskBits
..filterData.maskBits = maskBits,
);
}
}
/// Indicates a orientation of the ramp entrance/exit.
///
/// Used to know if ramps are looking up or down of the board.
@ -79,17 +96,16 @@ abstract class RampOpening extends BodyComponent {
@override
Body createBody() {
final fixtureDef = FixtureDef(shape)..isSensor = true;
final fixtureDef = FixtureDef(shape)
..isSensor = true
..filter.categoryBits = _categoryBits;
final bodyDef = BodyDef()
..userData = this
..position = _position
..type = BodyType.static;
final body = world.createBody(bodyDef);
body.createFixture(fixtureDef).filterData.categoryBits = _categoryBits;
return body;
return world.createBody(bodyDef)..createFixture(fixtureDef);
}
}

Loading…
Cancel
Save