How to align sprites sequentially in a line and extract them as a png format with TexturePacker?
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');
...
}
}