avocado-old/packages/entity/traits/positioned.js

62 lines
1.1 KiB
JavaScript
Raw Normal View History

2019-03-17 23:45:48 -05:00
import {compose} from '@avocado/core';
import {simpleState, Trait} from '../trait';
const decorate = compose(
2019-03-18 20:05:00 -05:00
simpleState('x', {
track: true,
}),
simpleState('y', {
track: true,
}),
2019-03-17 23:45:48 -05:00
);
class PositionedBase extends Trait {
static defaultState() {
return {
x: 0,
y: 0,
};
}
get position() {
return [
this.state.get('x'),
this.state.get('y'),
];
}
set position([x, y]) {
2019-03-19 10:19:23 -05:00
const positionChanged = x !== entity.x || y !== entity.y;
const lastPosition = entity.position;
this.entity.x = x;
this.entity.y = y;
if (positionChanged) {
this.entity.emit('positionChanged', entity.position, lastPosition);
}
2019-03-17 23:45:48 -05:00
}
listeners() {
return {
xChanged: (x, oldX) => {
this.entity.emit(
'positionChanged',
this.entity.position,
[oldX, this.entity.y]
);
},
yChanged: (y, oldY) => {
this.entity.emit(
'positionChanged',
this.entity.position,
[this.entity.x, oldY]
);
},
}
}
2019-03-17 23:45:48 -05:00
}
export class Positioned extends decorate(PositionedBase) {}