-
Notifications
You must be signed in to change notification settings - Fork 0
/
Animation.js
59 lines (52 loc) · 1.09 KB
/
Animation.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
function Animation(image, tpf, w, h, x, y) {
var that = this;
this.spriteSheet = image;
this.active = false;
this.width = w;
this.height = h;
this.x = x;
this.y = y;
this.rows = image.height / this.height;
this.cols = image.width / this.width;
this.loop = false;
this.tpf = tpf; // ticks per frame
this.frame = 0;
this.ticks = 0;
this.play = function() {
that.active = true;
that.ticks = 0;
that.frame = 0;
}
this.stop = function() {
that.active = false;
that.ticks = 0;
that.frame = 0;
}
this.update = function(dt) {
if (!that.active) return;
that.ticks++;
if (that.ticks >= that.tpf) {
that.ticks = 0;
that.frame += 1;
}
if (that.frame >= that.rows * that.cols) {
if (that.loop) that.frame = 0;
else {
that.frame = 0;
that.active = false;
}
}
}
this.draw = function(ctx) {
if (!that.active) return;
ctx.drawImage(that.spriteSheet,
Math.floor(that.frame % that.cols) * that.width,
Math.floor(that.frame / that.cols) * that.height,
that.width,
that.height,
this.x,
this.y,
that.width,
that.height);
}
}