Hi,
I'm a new member in the java game's world and my intent is to write my first game: a "shooting game".
I wanna give an animation to the enemy sprites, I've seen the "Animation.java" class in the "New Riders Developing Games In Java" document and I would like to know if is good or if there are best ways to build animation.
This is the code:
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
| import java.awt.Image; import java.util.ArrayList;
public class Animation {
private ArrayList frames; private int currFrameIndex; private long animTime; private long totalDuration;
public Animation() { frames = new ArrayList(); totalDuration = 0; start(); }
public synchronized void addFrame(Image image, long duration) { totalDuration += duration; frames.add(new AnimFrame(image, totalDuration)); }
public synchronized void start() { animTime = 0; currFrameIndex = 0; }
public synchronized void update(long elapsedTime) { if (frames.size() > 1) { animTime += elapsedTime;
if (animTime >= totalDuration) { animTime = animTime % totalDuration; currFrameIndex = 0; }
while (animTime > getFrame(currFrameIndex).endTime) { currFrameIndex++; } } }
public synchronized Image getImage() { if (frames.size() == 0) { return null; } else { return getFrame(currFrameIndex).image; } }
private AnimFrame getFrame(int i) { return (AnimFrame)frames.get(i); }
private class AnimFrame {
Image image; long endTime;
public AnimFrame(Image image, long endTime) { this.image = image; this.endTime = endTime; } } } |
