silphius/app/ecs/components/sprite.js
2024-07-25 10:48:22 -05:00

91 lines
2.4 KiB
JavaScript

import Component from '@/ecs/component.js';
export default class Sprite extends Component {
instanceFromSchema() {
return class SpriteInstance extends super.instanceFromSchema() {
$$sourceJson = {};
get anchor() {
return {x: this.anchorX, y: this.anchorY};
}
get animation() {
return super.animation;
}
set animation(animation) {
if (this.$$animation === animation) {
return;
}
super.animation = animation;
// eslint-disable-next-line no-self-assign
this.frame = this.frame;
}
get frame() {
return super.frame;
}
set frame(frame) {
super.frame = this.frames ? frame % this.frames : 0;
}
get frames() {
if (
!this.animation
|| !this.$$sourceJson.animations
|| !(this.animation in this.$$sourceJson.animations)
) {
return 0;
}
return this.$$sourceJson.animations[this.animation].length;
}
hasAnimation(animation) {
if (
!this.$$sourceJson.animations
|| !(animation in this.$$sourceJson.animations)
) {
return false;
}
return true;
}
get rotates() {
if (!this.$$sourceJson.meta) {
return false;
}
return 'rotation' in this.$$sourceJson.meta;
}
get rotation() {
if (!this.$$sourceJson.meta) {
return 0;
}
return this.$$sourceJson.meta.rotation;
}
get scale() {
return {x: this.scaleX, y: this.scaleY};
}
toNet() {
// eslint-disable-next-line no-unused-vars
const {elapsed, ...rest} = super.toNet();
return rest;
}
};
}
async load(instance) {
instance.$$sourceJson = await this.ecs.readJson(instance.source);
}
markChange(entityId, key, value) {
if ('elapsed' === key) {
return;
}
super.markChange(entityId, key, value);
}
static properties = {
alpha: {defaultValue: 1, type: 'float32'},
anchorX: {defaultValue: 0.5, type: 'float32'},
anchorY: {defaultValue: 0.5, type: 'float32'},
animation: {type: 'string'},
elapsed: {type: 'float32'},
frame: {type: 'uint16'},
isAnimating: {defaultValue: 1, type: 'uint8'},
scaleX: {defaultValue: 1, type: 'float32'},
scaleY: {defaultValue: 1, type: 'float32'},
source: {type: 'string'},
speed: {type: 'float32'},
};
}