Search code examples
flutterflame

Tappables miss when using CameraComponent


I followed the documentation on the Flame site to create a Klondike game skeleton, and now am trying to apply the same ideas towards creating a board game. I like using the CameraComponent because it allows for easily resizing the game area as the browser size changes, but I've found that when mixed with Tappable Components the tap events tend to "miss", or not line up with what's visible on the screen. Here's a minimal example:

import 'package:flame/components.dart';
import 'package:flame/experimental.dart';
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flutter/material.dart';

void main() {
  final game = MyFlameGame();
  runApp(GameWidget(game: game));
}

class MyFlameGame extends FlameGame with HasTappables {
  @override
  Future<void> onLoad() async {
    final myComponent = MyComponent()
      ..size = Vector2(50, 50)
      ..position = Vector2(250, 250);

    final world = World();
    world.add(myComponent);
    add(world);

    final camera = CameraComponent(world: world)
      ..viewfinder.visibleGameSize = Vector2(1000, 1000)
      ..viewfinder.position = Vector2(500, 0)
      ..viewfinder.anchor = Anchor.topCenter;
    add(camera);
  }
}

class MyComponent extends PositionComponent with Tappable {
  @override
  bool get debugMode => true;

  @override
  bool onTapUp(TapUpInfo info) {
    print('tap up');
    return true;
  }

  @override
  bool onTapDown(TapDownInfo info) {
    print('tap down');
    return true;
  }
}

If you resize the window and click within the box, I'd expect to see console logs but they sometimes don't appear. Occasionally I'm able to find the real Tappable position in the black area which will trigger the console messages. Is there a way to configure the Tappable components to line up with what's visible through the CameraComponent viewport?


Solution

  • This is a known bug in the CameraComponent, or maybe not a bug, it just hasn't been implemented yet. This is one of the reasons why the CameraComponent is still classified as experimental.

    The work is ongoing though, and you can get updated by following this issue.