|
1 | 1 | package eu.barkmin.processing.scratch; |
2 | 2 |
|
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 | + } |
4 | 64 | } |
0 commit comments