-
Notifications
You must be signed in to change notification settings - Fork 0
/
AnimationSystem.js
61 lines (56 loc) · 1.55 KB
/
AnimationSystem.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
//--------------------
/**
* AnimationSystem
**/
var AnimationSystem = function(resources) {
this._world = null;
this._res = resources;
};
AnimationSystem.prototype.addToWorld = function(world) {
this._world = world;
};
AnimationSystem.prototype.removeFromWorld = function() {
this._world = null;
};
AnimationSystem.prototype.step = function(delta) {
var res = this._res;
var ents = this._world.getEntities('animated', 'sprite');
for (var i = 0, ent; !!(ent = ents[i]); i++) {
var animated = ent.get('animated');
var animation = res.animations[animated.animation];
var timestep = 1 / animation.fps;
var updated = false;
var frameIndex = animated.currentFrameIndex;
if (!frameIndex && frameIndex !== 0) {
frameIndex = 0;
animated.frameElapsed = 0;
updated = true;
} else {
animated.frameElapsed += delta / 1000.0;
while (animated.frameElapsed >= timestep) {
animated.frameElapsed -= timestep;
frameIndex++;
if (frameIndex >= animation.frames.length) {
if (animation.loop) {
frameIndex = 0;
} else {
frameIndex--;
ent.del('animated');
}
}
updated = true;
}
}
if (updated) {
var frame = animation.frames[frameIndex];
var sprite = ent.get('sprite');
sprite.image = frame.image;
var rect = frame.rect;
sprite.x = rect.x;
sprite.y = rect.y;
sprite.w = rect.width;
sprite.h = rect.height;
animated.currentFrameIndex = frameIndex;
}
}
};