Search code examples
flutterdartrenderingflame

How do you sort the render order of sprites in Flame (Flutter) at runtime?


What's the most concise (and ideally, most efficient) approach to sort the rendering order of sprites in the game scene at runtime, post add()-ing the objects to the scene? Is there a built-in property on SpriteComponent or SpriteAnimationGroupComponent objects that can receive an int to indicate the sort order and override the implicit sort order? I wanted to confirm there wasn't something already implemented in Flame prior to implementing my own Z-sorting algorithm from scratch.

Thanks!


Solution

  • The z-index order is called priority in Flame. If you know before you add the component to the game what priority it has, you can send in the named field priority to the constructor, like this:

    final myComponent = SpriteComponent(sprite: mySprite, priority: 5);
    

    On the other hand, if you don't know what priority the component will have (or if you want to change it during the lifetime of the component) you have to use the method changePriority on the FlameGame class.

    class MyGame extends FlameGame {
      ...
    }
    
    final myGame = MyGame();
    myGame.changePriority(myComponent, 1);
    

    There is also the method on Component called changePriorityWithoutResorting which can be used before the component is added to a game. But if the component is already added, this method won't have any effect until the component is re-added to the game.