Skip to content

Commit 3e02e91

Browse files
author
Mike Barkmin
committed
Add animated sprite
1 parent 8f5bd06 commit 3e02e91

1 file changed

Lines changed: 61 additions & 1 deletion

File tree

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,64 @@
11
package eu.barkmin.processing.scratch;
22

3-
public class ScratchAnimatedSprite {
3+
import java.util.HashMap;
4+
5+
public class ScratchAnimatedSprite extends ScratchSprite {
6+
7+
private HashMap<String, String[]> animations = new HashMap<>();
8+
private int animationInterval = 120;
9+
private int animationFrame = 0;
10+
private boolean animationPlayed = false;
11+
12+
public void addAnimation(String name, String pattern, int frames) {
13+
String[] animation = new String[frames];
14+
for (int i = 0; i < animation.length; i++) {
15+
String costumeName = "_animation_" + name + "_" + i;
16+
String file = String.format(pattern, i+1);
17+
this.addCostume(costumeName, file);
18+
animation[i] = costumeName;
19+
}
20+
animations.put(name, animation);
21+
}
22+
23+
public void playAnimation(String name) {
24+
this.playAnimation(name,false);
25+
}
26+
27+
public void playAnimation(String name, boolean once) {
28+
if (this.getTimer("animation") == null) {
29+
this.addTimer("animation");
30+
}
31+
if (this.getTimer("animation").everyMillis(animationInterval)) {
32+
String[] animation = animations.get(name);
33+
if (!animationPlayed && animationFrame != animation.length - 1 || !once) {
34+
animationFrame = (animationFrame + 1) % animation.length;
35+
this.switchCostume(animation[animationFrame]);
36+
}
37+
}
38+
}
39+
40+
public void resetAnimation() {
41+
animationFrame = 0;
42+
animationPlayed = false;
43+
}
44+
45+
public void setAnimationInterval(int interval) {
46+
animationInterval = interval;
47+
}
48+
49+
public int getAnimationInterval() {
50+
return animationInterval;
51+
}
52+
53+
public int getAnimationFrame() {
54+
return animationFrame;
55+
}
56+
57+
public void setAnimationFrame(int frame) {
58+
animationFrame = frame;
59+
}
60+
61+
public boolean isAnimationPlayed() {
62+
return animationPlayed;
63+
}
464
}

0 commit comments

Comments
 (0)