Search code examples
flutterflame

How to move a Vector2 using PositionComponent with Flame/Flutter?


I am trying to move a Vector2's x position, the update is being called, the x value is changing but the white square component does not move, what am I missing?

i am using flame 1.0.0-releasecandidate.11.

screenshot

import 'dart:ui';
import 'package:flame/components.dart';
import 'package:flame/palette.dart';

class PlayerComponent extends PositionComponent {

  static const squareSize = 128.0;
  static Paint white = BasicPalette.white.paint();

  @override
  void render(Canvas canvas) {
    canvas.drawRect(size.toRect(), white);
    super.render(canvas);
  }

  @override
  void update(double dt) {
    x += 10 * dt;
    print(x);
    super.update(dt);
  }

  @override
  void onMount() {
    super.onMount();
    size.setValues(squareSize, squareSize);
    anchor = Anchor.center;
  }

}

class AnimalVillageGame extends BaseGame {

  @override
  Future<void> onLoad() async {

    add(PlayerComponent()
      ..x = 100
      ..y = 100
    );
  }

}

Solution

  • You render method renders the size as a zero-bound rectangle, size.toRect() returns a Rect at the position 0,0.

    Instead you can use the toRect method from the PositionComponent class:

      @override
      void render(Canvas canvas) {
        canvas.drawRect(toRect(), white);
        super.render(canvas);
      }
    

    This method returns the rect of the component, based on the x, y position and the size.

    Edit: As mentioned by spydon, the super.render is called after the rendering to the canvas, it would be better to call the super method first as it will automatically handle things like translation, rotation, etc for you.

    It prepares the canvas for your own rendering.