-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanimator.js
54 lines (44 loc) · 1.49 KB
/
animator.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
class Animator {
constructor(spritesheet, xStart, yStart, width, height, frameCount, frameDuration, framePadding, reverse, loop) {
Object.assign(this, { spritesheet, xStart, yStart, height, width, frameCount, frameDuration, framePadding, reverse, loop });
this.elapsedTime = 0;
this.totalTime = this.frameCount * this.frameDuration;
};
drawFrame(tick, ctx, x, y, scale, isHidden) {
this.elapsedTime += tick;
if (this.isDone()) {
if (this.loop) {
this.elapsedTime -= this.totalTime;
} else {
return;
}
}
let frame = this.currentFrame();
if (this.reverse) frame = this.frameCount - frame - 1;
if (isHidden) {
ctx.drawImage(this.spritesheet, 0, 0, 0, 0);
} else {
ctx.drawImage(
this.spritesheet,
this.xStart + frame * (this.width + this.framePadding),
this.yStart, //source from sheet
this.width,
this.height,
x,
y,
this.width * scale,
this.height * scale
);
if (PARAMS.DEBUG) {
ctx.strokeStyle = 'Green';
ctx.strokeRect(x, y, this.width * scale, this.height * scale);
}
}
};
currentFrame() {
return Math.floor(this.elapsedTime / this.frameDuration);
};
isDone() {
return (this.elapsedTime >= this.totalTime);
};
};