-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathanimated_image.js
93 lines (77 loc) · 2.14 KB
/
animated_image.js
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
// Manages an animated image. Assumes that while it is active,
// get_image is called once per game loop
// Defaults to starting immediately
// Unless you call loop, will only run through the images once
// spec:
// All optional
// anim_rate : the number of frames to display each image
// reverse : whether to go backwards in the images when you reach the end or not
var animated_image = function(image_name, spec) {
// obj to return
var obj = [];
// private vars
var all_images = image_manager.get_images(image_name);
all_images.sort(
function(i1, i2) {
//return i1.path < i2.path;
return i1.path < i2.path ? -1 : (i1.path > i2.path ? 1 : 0);
}
);
//for_each(all_images, function(i) { console.log(i.path); });
var curr_index = 0;
var active = true;
var loop = false;
var rate_counter = 0; // Goes from 0 to anim_rate - 1
var anim_rate = spec.anim_rate || 3;
// If we are reversing, add all the images in the opposite
// order to all_images
if (spec.reverse || false) {
for (var i = (all_images.length - 1); i >=0; i--) {
all_images.push(all_images[i]);
}
}
//public methods
obj.start = function() {
active = true;
};
obj.pause = function() {
active = false;
};
obj.loop = function() {
loop = true;
};
obj.is_finished = function() {
// changed to && cuz it should be not looping
// and at the end to be finished
return (!loop && curr_index === (all_images.length - 1));
};
// Returns the current image
obj.get_frame = function() {
var curr_image = all_images[curr_index].image;
update();
return curr_image;
};
obj.set_rate = function(r) {
anim_rate = r;
};
// private methods
var update = function() {
if (active) {
if (rate_counter >= (anim_rate - 1)) {
next_frame();
rate_counter = 0;
}
else {
rate_counter++;
}
}
};
var next_frame = function() {
// If not 'at the end and not looping',
// increment curr_index, restarting if we reach the end
if (!(curr_index === all_images.length && !loop)) {
curr_index = (curr_index + 1) % all_images.length;
}
}
return obj;
}