asdf-games/lib/AnimManager.js

65 lines
1.1 KiB
JavaScript
Raw Normal View History

class Anim {
constructor(frames, rate) {
this.frames = frames;
this.rate = rate;
this.reset();
}
2020-03-22 13:57:15 +01:00
reset() {
this.frame = this.frames[0];
this.curFrame = 0;
this.curTime = 0;
}
update(dt) {
const { rate, frames } = this;
if ((this.curTime += dt) > rate) {
this.curFrame++;
this.frame = frames[this.curFrame % frames.length];
this.curTime -= rate;
}
}
}
2020-03-22 13:57:15 +01:00
class AnimManager {
2020-03-22 13:57:15 +01:00
constructor(e = { x: 0, y: 0 }) {
this.anims = {};
this.running = false;
this.frameSource = e.frame || e;
2020-03-22 13:57:15 +01:00
this.current = null;
}
2020-03-22 13:57:15 +01:00
add(name, frames, speed) {
this.anims[name] = new Anim(frames, speed);
return this.anims[name];
}
2020-03-22 13:57:15 +01:00
update(dt) {
const { current, anims, frameSource } = this;
if (!current) {
return;
}
const anim = anims[current];
anim.update(dt);
2020-03-22 13:57:15 +01:00
// Sync the tileSprite frame
frameSource.x = anim.frame.x;
frameSource.y = anim.frame.y;
}
2020-03-22 13:57:15 +01:00
play(anim) {
const { current, anims } = this;
2020-03-22 13:57:15 +01:00
if (anim === current) {
return;
}
this.current = anim;
anims[anim].reset();
}
2020-03-22 13:57:15 +01:00
stop() {
this.current = null;
}
}
2020-03-22 13:57:15 +01:00
module.exports = AnimManager;