flutterdartflame

Rotating point (anchor) for SpriteComponent


I'm playing around with Flame and Flutter and trying to add a SpriteComponent that rotates around its center. I'm a beginner, so bare with me.

It works when I do the following:

class Player extends SpriteComponent with HasGameRef<MyGame> {
  Player({required this.sprite}) : super();

  final Sprite sprite;
  late SpriteComponent player;

  @override
  FutureOr<void> onLoad() {
    player = SpriteComponent(
      sprite: sprite,
      position: Vector2(0, 0),
      size: Vector2(150, 80),
      anchor: Anchor.center,
    );
    debugMode = true;
    add(player);
    return super.onLoad();
  }

  @override
  void update(double dt) {
    angle += 0.01;
    super.update(dt);
  }
}

So it looks like so:

enter image description here

But when I want to move the Sprite a bit and add the line:

position: Vector2(200, 200),

enter image description here

And now it rotates still around the corner on the top...how do I rotate the Sprite in its own center?


Solution

  • You have a SpriteComponent inside of your Player component (which is also a SpriteComponent), since you are using the same sprite on both of those components I'm fairly certain you only want one of those.

    If you remove the inner player you'll end up with something like this, which should be what you want:

    class Player extends SpriteComponent with HasGameRef<MyGame> {
      Player({required this.sprite}) : super(
        position: Vector2(0, 0),
        size: Vector2(150, 80),
        anchor: Anchor.center,
      );
    
      @override
      Future<void> onLoad() {
        super.onLoad();
        debugMode = true;
      }
    
      @override
      void update(double dt) {
        super.update(dt);
        angle += 0.01;
      }
    }