-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnimation.java
More file actions
92 lines (76 loc) · 2.19 KB
/
Copy pathAnimation.java
File metadata and controls
92 lines (76 loc) · 2.19 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
import java.awt.Image;
import java.util.ArrayList;
/**
* Animation utility class for frame-based animation.
*/
public class Animation {
private ArrayList<AnimFrame> frames;
private int currFrameIndex;
private long animTime;
private long startTime;
private long totalDuration;
private boolean loop;
private boolean isActive;
public Animation() {
frames = new ArrayList<AnimFrame>();
totalDuration = 0;
loop = true;
isActive = false;
}
public Animation(boolean loop) {
frames = new ArrayList<AnimFrame>();
totalDuration = 0;
this.loop = loop;
isActive = false;
}
public synchronized void addFrame(Image image, long duration) {
totalDuration += duration;
frames.add(new AnimFrame(image, totalDuration));
}
public synchronized void start() {
isActive = true;
animTime = 0;
currFrameIndex = 0;
startTime = System.currentTimeMillis();
}
public synchronized void update() {
if (!isActive || frames.size() <= 1)
return;
long currTime = System.currentTimeMillis();
long elapsedTime = currTime - startTime;
startTime = currTime;
animTime += elapsedTime;
if (animTime >= totalDuration) {
if (loop) {
animTime = animTime % totalDuration;
currFrameIndex = 0;
} else {
isActive = false;
return;
}
}
while (animTime > getFrame(currFrameIndex).endTime) {
currFrameIndex++;
}
}
public synchronized Image getImage() {
if (frames.size() == 0) {
return null;
}
return getFrame(currFrameIndex).image;
}
private AnimFrame getFrame(int i) {
return frames.get(i);
}
public boolean isActive() {
return isActive;
}
private class AnimFrame {
Image image;
long endTime;
AnimFrame(Image image, long endTime) {
this.image = image;
this.endTime = endTime;
}
}
}