the-world-engine
Version:
three.js based, unity like game engine for browser
82 lines (79 loc) • 2.04 kB
JavaScript
import { Component } from "../../hierarchy_object/Component";
import { AsyncImageLoader } from "../helper/AsyncImageLoader";
import { CssSpriteRenderer } from "../render/CssSpriteRenderer";
export class SpriteAnimator extends Component {
disallowMultipleComponent=true;
requiredComponents=[ CssSpriteRenderer ];
na=null;
oa=new Map;
ma=null;
pa=null;
la=0;
_a=false;
ua=2;
da=0;
fa=null;
awake() {
this.na = this.gameObject.getComponent(CssSpriteRenderer);
if (this.fa !== null) {
this.playAnimation(this.fa);
this.fa = null;
}
}
update() {
if (!this._a) return;
this.da += this.engine.time.deltaTime;
if (this.da >= this.ua) {
this.da = 0;
this.la += 1;
if (this.la >= this.pa.length) {
this.la = 0;
}
this.na.setImage(this.pa[this.la]);
}
}
playAnimation(i) {
if (this.na === null) {
this.fa = i;
return;
}
if (this.ma === i) return;
this.ma = i;
const t = this.oa.get(i);
if (t === undefined) {
throw new Error(`Animation "${i}" does not exist.`);
}
this.pa = t;
this.la = 0;
this.na.setImage(t[0]);
this._a = true;
}
stopAnimation() {
this._a = false;
this.fa = null;
}
addAnimation(i, t) {
if (t.length === 0) {
console.warn(`Animation "${i}" has no frames.`);
return;
}
this.oa.set(i, t);
}
addAnimationFromPath(i, t) {
const e = [];
for (let i = 0; i < t.length; ++i) {
const n = new Image;
n.src = t[i];
e.push(n);
}
AsyncImageLoader.loadImages(e).then((() => {
this.addAnimation(i, e);
}));
}
get frameDuration() {
return this.ua;
}
set frameDuration(i) {
this.ua = i;
}
}