Search code examples
flutterflame

Attaching components so they move together


Is it possible with flame components to attach them to other components so that their position is updated when the "parent" component moves?

I want to have a hitbox component and attached to it the player sprite, name tag and so on with an xy-offset.


Solution

  • You can use any PositionComponent (most components in Flame inherit from PositionComponent) and add children to it.

    So here for example we create a simple square which has two square children which move, scale and rotate together with the parent:

    class Square extends PositionComponent {
      Square(Vector2 position, Vector2 size, {double angle = 0})
          : super(
              position: position,
              size: size,
              angle: angle,
            );
    }
    
    class ParentSquare extends Square with HasGameRef {
      ParentSquare(Vector2 position, Vector2 size) : super(position, size);
    
      @override
      Future<void> onLoad() async {
        super.onLoad();
        // All positions here are in relation to the parent's position
        add(Square(Vector2(100, 100), Vector2(50, 50), angle: 2));
        add(Square(Vector2(160, 100), Vector2(50, 50), angle: 3));
      }
    }
    

    An example can be seen here. (If you press <> you'll see the code for the example)