flutterdartflame

How can I change anchor to Anchor.center in SpriteComponent in Flutter Flame?


I'm trying to change my object(Horse()) anchor point to Anchor.center in the creation of the object. But I wasn't able to. If I change it inside FlameGame using horse.anchor = Anchor.center it works but I want to create it with Anchor.center.

import 'package:flame/components.dart';

class Horse extends SpriteComponent {
  final String name;
  static const double spriteSize = 64;

  @override
  set anchor(Anchor anchor) {
    super.anchor = Anchor.center;
  }

  @override
  Future<void> onLoad() async {
    sprite = await Sprite.load('$name.jpg');
  }

  Horse(this.name) : super(size: Vector2.all(spriteSize));
}

Solution

  • You can pass in the anchor directly to the super constructor:

    import 'package:flame/components.dart';
    
    class Horse extends SpriteComponent {
      Horse(this.name) : super(size: Vector2.all(spriteSize), anchor: Anchor.center);
    
      final String name;
      static const double spriteSize = 64;
    
      @override
      Future<void> onLoad() async {
        sprite = await Sprite.load('$name.jpg');
      }
    }
    

    If you don't want to extend SpriteComponent you can also do this:

    final sprite = await loadSprite('horse.jpg');
    final spriteSize = 64;
    
    final component = SpriteComponent(
      sprite: sprite,
      size: Vector2.all(spriteSize),
      anchor: Anchor.center,
    );