Search code examples
flutterdartflame

Tap doesn't register correctly with FixedResolutionViewport


Using HasTappableComponents with TapCallbacks gives strange results in a FixedResolutionViewport game. The router seems to render my component centered and then the tap seems to register on the place where it would be if my component wasn't centered. The image below shows where the tap registers with a red arrow. Does anyone know what is wrong with this code?

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

class TestGame extends FlameGame with HasTappableComponents {
  @override
  Future<void>? onLoad() async {
    camera.viewport = FixedResolutionViewport(
      Vector2(540, 960),
    );
    await add(
      RouterComponent(
        initialRoute: 'home',
        routes: {
          'home': Route(SceneComponent.new),
        },
      ),
    );
    return super.onLoad();
  }
}

class SceneComponent extends PositionComponent with HasGameRef<TestGame> {
  @override
  Future<void>? onLoad() async {
    size = gameRef.size;
    await add(
      TestComponent(
        position: Vector2(
          size.x * 0.5,
          size.y * 0.5,
        ),
        size: Vector2(100, 100),
        anchor: Anchor.center,
      ),
    );
    return super.onLoad();
  }

  @override
  void render(Canvas canvas) {
    canvas.drawRect(size.toRect(), Paint()..color = Color.fromARGB(255, 0, 255, 119));
    return super.render(canvas);
  }
}

class TestComponent extends PositionComponent with TapCallbacks {
  TestComponent({
    super.position,
    super.size,
    super.scale,
    super.angle,
    super.nativeAngle,
    super.anchor,
    super.children,
    super.priority,
  });

  @override
  void onTapDown(TapDownEvent event) {
    print('tap');
    super.onTapDown(event);
  }

  @override
  void render(Canvas canvas) {
    canvas.drawRect(
      size.toRect(),
      Paint()..color = Color.fromARGB(255, 255, 0, 0),
    );
  }
}

enter image description here


Solution

  • Seems like it is a bug at the moment according to answers in discord. Issue can be found here.

    https://github.com/flame-engine/flame/issues/2141