/
Sprite.java
57 lines (47 loc) · 1.28 KB
/
Sprite.java
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
package cookbook.dungeon.core;
import playn.core.*;
import playn.core.util.Clock;
import static playn.core.PlayN.*;
public class Sprite {
private final Image.Region _tile;
private final int _tilesPerRow;
private final float _msPerFrame;
private float _nextFrame;
private float _rowY;
private int _frame;
public final int width, height;
public final ImageLayer layer;
public Sprite (Image image, int tileWid, int tileHei, int tilesPerRow, float msPerFrame) {
_tile = image.subImage(0, 0, tileWid, tileHei);
_tilesPerRow = tilesPerRow;
_msPerFrame = msPerFrame;
_nextFrame = msPerFrame;
width = tileWid;
height = tileHei;
layer = graphics().createImageLayer(_tile);
layer.setOrigin(tileWid/2, tileHei/2);
}
public void setRow (int row) {
_rowY = row * height;
updateImage();
}
public void idle () {
_nextFrame = 0;
if (_frame != 0) {
_frame = 0;
updateImage();
}
}
public void paint (Clock clock) {
_nextFrame -= clock.dt();
int frame = _frame;
while (_nextFrame < 0) {
_nextFrame += _msPerFrame;
_frame = (_frame + 1) % _tilesPerRow;
}
if (_frame != frame) updateImage();
}
private void updateImage () {
_tile.setBounds(_frame * width, _rowY, width, height);
}
}