forked from flame-engine/flame
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspritesheet.dart
More file actions
107 lines (92 loc) · 2.36 KB
/
spritesheet.dart
File metadata and controls
107 lines (92 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import 'package:meta/meta.dart';
import 'sprite.dart';
import 'animation.dart';
import 'dart:ui';
/// Utility class to help extract animations and sprites from a spritesheet image
class SpriteSheet {
int textureWidth;
int textureHeight;
int columns;
int rows;
List<List<Sprite>> _sprites;
SpriteSheet({
@required String imageName,
@required this.textureWidth,
@required this.textureHeight,
@required this.columns,
@required this.rows,
}) {
_sprites = List.generate(
rows,
(y) => List.generate(
columns,
(x) => _mapImagePath(imageName, textureWidth, textureHeight, x, y),
),
);
}
Sprite _mapImagePath(
String imageName,
int textureWidth,
int textureHeight,
int x,
int y,
) {
return Sprite(
imageName,
x: (x * textureWidth).toDouble(),
y: (y * textureHeight).toDouble(),
width: textureWidth.toDouble(),
height: textureHeight.toDouble(),
);
}
SpriteSheet.fromImage({
@required Image image,
@required this.textureWidth,
@required this.textureHeight,
@required this.columns,
@required this.rows,
}) {
_sprites = List.generate(
rows,
(y) => List.generate(
columns,
(x) => _mapImage(image, textureWidth, textureHeight, x, y),
),
);
}
Sprite _mapImage(
Image image,
int textureWidth,
int textureHeight,
int x,
int y,
) {
return Sprite.fromImage(
image,
x: (x * textureWidth).toDouble(),
y: (y * textureHeight).toDouble(),
width: textureWidth.toDouble(),
height: textureHeight.toDouble(),
);
}
Sprite getSprite(int row, int column) {
final Sprite s = _sprites[row][column];
assert(s != null, 'No sprite found for row $row and column $column');
return s;
}
/// Creates an animation from this SpriteSheet
///
/// An [from] and a [to] parameter can be specified to create an animation from a subset of the columns on the row
Animation createAnimation(int row,
{double stepTime, bool loop = true, int from = 0, int to}) {
final spriteRow = _sprites[row];
assert(spriteRow != null, 'There is no row for $row index');
to ??= spriteRow.length;
final spriteList = spriteRow.sublist(from, to);
return Animation.spriteList(
spriteList,
stepTime: stepTime,
loop: loop,
);
}
}