fluttertexturepackerflame

How to align sprites sequentially in a line and extract them as a png format with TexturePacker?


I want to align 15 picture from this pack in one line using TexturePacker and create a png file as sprite sheet to create an animation using FireAtlas afterward. I tried a lot but couldn't create such output. I am using Flame library in Flutter and there is no output for Flame in TexturePacker software, so I have to use many tools to get the desired output.


Solution

  • flame_texturepacker is now updated to flame 1.0.0 and nullsafety, so you can just depend on flame_texturepacker: ^2.0.0.

    Old answer:

    Something like this should work:

    import 'dart:convert';
    import 'package:flame/flame.dart';
    import 'package:flame/sprite.dart';
    
    extension TexturePackerExtension on Game {
      Future<List<Sprite>> loadTexturePack(
        String imagePath,
        String dataPath,
      ) async {
        final json = await Flame.assets.readJson(dataPath)
            as Map<String, Map<String, dynamic>>;
        final image = await Flame.images.load(imagePath);
    
        final sprites = json['frames']?.values.map((dynamic value) {
          final frameData = value['frame'] as Map<String, int>;
          final x = frameData['x']!;
          final y = frameData['y']!;
          final width = frameData['w']!;
          final height = frameData['h']!;
    
          return Sprite(
            image,
            srcPosition: Vector2(x.toDouble(), y.toDouble()),
            srcSize: Vector2(width.toDouble(), height.toDouble()),
          );
        });
    
        return sprites?.toList() ?? [];
      }
    }
    

    Converted from flame_texturepacker to Flame version 1.0.0.

    Just import it in your game class file and call it:

    import texture_packer_extension.dart;
    
    class MyGame extends FlameGame {
      ...
    
      @override
      Future<void> onLoad() async {
        super.onLoad();
        final sprites = await loadTexturePack('myImage.png', 'myJson.json');
        ...
      }
    }