fix: Use root game for gestures (#2756)

Since registering detectors won't work on a non-root game we have to register the dispatchers on the root game.
This commit is contained in:
Lukas Klingsbo
2023-09-21 19:34:47 +02:00
committed by GitHub
parent 521e56b6d2
commit f5d0cb3856
6 changed files with 37 additions and 4 deletions

View File

@ -381,6 +381,8 @@ class Component {
@internal
static Game? staticGameInstance;
/// Fetches the nearest [FlameGame] ancestor to the component.
FlameGame? findGame() {
assert(
staticGameInstance is FlameGame || staticGameInstance == null,
@ -393,6 +395,15 @@ class Component {
((this is FlameGame) ? (this as FlameGame) : _parent?.findGame());
}
/// Fetches the root [FlameGame] ancestor to the component.
FlameGame? findRootGame() {
var game = findGame();
while (game?.parent != null) {
game = game!.parent!.findGame();
}
return game;
}
/// Whether the children list contains the given component.
///
/// This method uses reference equality.

View File

@ -28,7 +28,7 @@ mixin DoubleTapCallbacks on Component {
@override
void onMount() {
super.onMount();
final game = findGame()!;
final game = findRootGame()!;
if (game.findByKey(const DoubleTapDispatcherKey()) == null) {
final dispatcher = DoubleTapDispatcher();
game.registerKey(const DoubleTapDispatcherKey(), dispatcher);

View File

@ -65,7 +65,7 @@ mixin DragCallbacks on Component {
@mustCallSuper
void onMount() {
super.onMount();
final game = findGame()!;
final game = findRootGame()!;
if (game.findByKey(const MultiDragDispatcherKey()) == null) {
final dispatcher = MultiDragDispatcher();
game.registerKey(const MultiDragDispatcherKey(), dispatcher);

View File

@ -18,7 +18,7 @@ mixin PointerMoveCallbacks on Component {
}
static void onMountHandler(PointerMoveCallbacks instance) {
final game = instance.findGame()!;
final game = instance.findRootGame()!;
const key = MouseMoveDispatcherKey();
if (game.findByKey(key) == null) {
final dispatcher = PointerMoveDispatcher();

View File

@ -22,7 +22,7 @@ mixin TapCallbacks on Component {
@mustCallSuper
void onMount() {
super.onMount();
final game = findGame()!;
final game = findRootGame()!;
if (game.findByKey(const MultiTapDispatcherKey()) == null) {
final dispatcher = MultiTapDispatcher();
game.registerKey(const MultiTapDispatcherKey(), dispatcher);

View File

@ -1121,6 +1121,28 @@ void main() {
});
});
group('findRootGame()', () {
testWithFlameGame('finds root game in nested game structure',
(game) async {
final component = Component();
await game.ensureAdd(
FlameGame(
children: [
Component(children: [component]),
],
),
);
expect(component.findRootGame(), game);
});
testWithFlameGame('finds root game in non-nested game structure',
(game) async {
final component = Component();
await game.ensureAdd(component);
expect(component.findRootGame(), game);
});
});
group('miscellaneous', () {
testWithFlameGame('childrenFactory', (game) async {
final component0 = Component();