-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanimator.js
132 lines (104 loc) · 2.59 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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
'use strict';
// https://github.com/PiGames/Bomberman/blob/master/Bomberman/Animator.cpp
class Animator {
constructor() {
this.activeStateName = '';
this.activeStateInfo = null;
this.animationSpeed = 1;
this.delay = 0.5;
this.elapsedTime = 0;
this.sprite = null;
this.currentFrame = 0;
this.lastFrame = 0;
this.loop = false;
this.animIsPlaying = false;
this.states = new Map();
this.timeToChangeFrame = this.delay / this.animationSpeed;
}
addAnimationState(name, atlas, begin, end, autoPlay) {
let state = this.states.get(name);
if (!state) {
state = {
atlas,
beg: begin,
end,
};
this.states.set(name, state);
if (autoPlay) {
this.changeActiveState(name);
}
return true;
}
return false;
}
animate(dt) {
if (!this.animIsPlaying) return;
this.elapsedTime += dt;
if (this.elapsedTime > this.timeToChangeFrame) {
this.currentFrame++;
if (this.currentFrame > this.lastFrame) {
if (this.loop) {
this.currentFrame = this.activeStateInfo.beg;
} else {
this.currentFrame = this.activeStateInfo.end;
this.animIsPlaying = false;
}
}
this.activeStateInfo.atlas.setSpriteTextureByIndex(
this.sprite,
this.currentFrame
);
this.elapsedTime = 0;
}
}
changeActiveState(name) {
if (!this.sprite) return false;
const state = this.states.get(name);
if (!state) return false;
this.activeStateName = name;
this.activeStateInfo = state;
this.currentFrame = state.beg;
this.lastFrame = state.end;
this.activeStateInfo.atlas.setSpriteTextureByIndex(
this.sprite,
this.activeStateInfo.beg
);
this.animIsPlaying = true;
return true;
}
getActiveState() {
return this.activeStateName;
}
isPlaying() {
return this.animIsPlaying;
}
pause() {
this.animIsPlaying = false;
}
play() {
this.animIsPlaying = true;
}
setAnimationSpeed(speed) {
this.animationSpeed = speed;
if (this.animationSpeed < 0.0001) {
this.animationSpeed = 0.0001;
}
this.timeToChangeFrame = this.delay / this.animationSpeed;
}
setDelayBetweenFrames(delay) {
this.delay = delay;
if (this.delay < 0.0) this.delay = 0.0;
this.timeToChangeFrame = this.delay / this.animationSpeed;
}
setLoop(loop) {
this.loop = loop;
}
setSprite(sprite) {
this.sprite = sprite;
}
stop() {
this.changeActiveState(this.activeStateName);
this.pause();
}
}
module.exports = Animator;