mirror of
https://github.com/flame-engine/flame.git
synced 2025-11-01 10:38:17 +08:00
This PR is the second in a series of refactors that aim to simplify event handling in Flame. The approach is as follows:
Added the MultiTapDispatcher component, which contains the logic that used to be within the HasTappableComponents mixin. This component is internal; it mounts to a FlameGame directly, and ensures that it is a singleton.
Whenever any TapCallbacks component is added to a game, it automatically adds the MultiTapDispatcher component (unless there is already one), which in turn registers a tap gesture detector with GestureDetectorBuilder and rebuilds the game widget.
The end result is that now in order to make a component tappable you only need to add the TapCallbacks mixin to that component, everything else will be handled by the framework.
Consequently, the HasTappableComponents mixin is now empty and marked as deprecated.
62 lines
1.4 KiB
Dart
62 lines
1.4 KiB
Dart
import 'package:flame/components.dart';
|
|
import 'package:flame/experimental.dart';
|
|
import 'package:flame/game.dart';
|
|
|
|
enum ButtonState { unpressed, pressed }
|
|
|
|
class SpriteGroupExample extends FlameGame {
|
|
static const String description = '''
|
|
In this example we show how a `SpriteGroupComponent` can be used to create
|
|
a button which displays different sprites depending on whether it is pressed
|
|
or not.
|
|
''';
|
|
|
|
@override
|
|
Future<void> onLoad() async {
|
|
add(
|
|
ButtonComponent()
|
|
..position = size / 2
|
|
..size = Vector2(200, 50)
|
|
..anchor = Anchor.center,
|
|
);
|
|
}
|
|
}
|
|
|
|
class ButtonComponent extends SpriteGroupComponent<ButtonState>
|
|
with HasGameRef<SpriteGroupExample>, TapCallbacks {
|
|
@override
|
|
Future<void> onLoad() async {
|
|
final pressedSprite = await gameRef.loadSprite(
|
|
'buttons.png',
|
|
srcPosition: Vector2(0, 20),
|
|
srcSize: Vector2(60, 20),
|
|
);
|
|
final unpressedSprite = await gameRef.loadSprite(
|
|
'buttons.png',
|
|
srcSize: Vector2(60, 20),
|
|
);
|
|
|
|
sprites = {
|
|
ButtonState.pressed: pressedSprite,
|
|
ButtonState.unpressed: unpressedSprite,
|
|
};
|
|
|
|
current = ButtonState.unpressed;
|
|
}
|
|
|
|
@override
|
|
void onTapDown(_) {
|
|
current = ButtonState.pressed;
|
|
}
|
|
|
|
@override
|
|
void onTapUp(_) {
|
|
current = ButtonState.unpressed;
|
|
}
|
|
|
|
@override
|
|
void onTapCancel(_) {
|
|
current = ButtonState.unpressed;
|
|
}
|
|
}
|