skip to Main Content

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));
}

2

Answers


  1. Chosen as BEST ANSWER

    I changed my code to this and it now works but I don't think this is the ideal solution so I still want your answers pls

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

  2. 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,
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search