avocado-old/packages/topdown/traits/tile-entity.trait.js
2020-06-19 22:01:45 -05:00

89 lines
1.6 KiB
JavaScript

import {compose, Property} from '@avocado/core';
import {StateProperty, Trait} from '@avocado/entity';
import {Vector} from '@avocado/math';
const decorate = compose(
StateProperty('tileIndex', {
track: true,
}),
);
export default class TileEntity extends decorate(Trait) {
static defaultState() {
return {
tileIndex: 0,
};
}
static describeState() {
return {
tileIndex: {
type: 'number',
label: 'Tile index',
},
};
}
static type() {
return 'tile-entity';
}
destroy() {
this.removeTileEntity(this.entity.tileIndex);
}
addTileEntity(tileIndex) {
const layer = this.entity.layer;
if (!layer) {
return;
}
layer.addTileEntity(this.entity, tileIndex);
}
removeTileEntity(tileIndex) {
const layer = this.entity.layer;
if (!layer) {
return;
}
layer.removeTileEntity(this.entity, tileIndex);
}
setTileIndex() {
if (!this.entity.layer) {
return;
}
this.entity.tileIndex = this.entity.layer.indexAt(
Vector.floor(this.entity.tile)
);
}
listeners() {
return {
addedToLayer: (layer) => {
this.setTileIndex();
},
removedFromLayer: (layer) => {
layer.removeTileEntity(this.entity, Vector.floor(this.entity.tile));
},
tileChanged: () => {
this.setTileIndex();
},
tileIndexChanged: (oldTileIndex, newTileIndex) => {
this.removeTileEntity(oldTileIndex);
this.addTileEntity(newTileIndex);
},
traitAdded: (type) => {
this.setTileIndex();
},
};
}
}