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

70 lines
1.3 KiB
JavaScript
Raw Normal View History

2019-03-17 23:45:48 -05:00
import {compose} from '@avocado/core';
2019-04-10 21:02:42 -05:00
import {Vector} from '@avocado/math';
import {EventEmitter} from '@avocado/mixins';
2019-03-17 23:45:48 -05:00
2019-04-10 21:02:42 -05:00
import {Trait} from '../trait';
2019-03-17 23:45:48 -05:00
const decorate = compose(
2019-04-10 21:02:42 -05:00
EventEmitter,
Vector.Mixin('_position', 'x', 'y', {
2019-03-18 20:05:00 -05:00
track: true,
}),
2019-03-17 23:45:48 -05:00
);
2019-04-10 21:02:42 -05:00
// < 16768 will pack into 1 short per axe and give +/- 0.25 precision.
2019-03-17 23:45:48 -05:00
class PositionedBase extends Trait {
static defaultState() {
return {
x: 0,
y: 0,
};
}
2019-04-10 21:02:42 -05:00
initialize() {
this.on('_positionChanged', (oldPosition, newPosition) => {
const x = Math.floor(newPosition[0]) * 4;
const y = Math.floor(newPosition[1]) * 4;
this.state = this.state.set('x', x).set('y', y);
this.entity.emit('positionChanged', oldPosition, newPosition);
});
const x = this.state.get('x') / 4;
const y = this.state.get('y') / 4;
this._position = [x, y];
}
get position() {
return this._position;
}
set position(position) {
this._position = position;
}
transformPatchValue(key, value) {
if (-1 !== ['x', 'y'].indexOf(key)) {
return value / 4;
}
super.transformPatchValue(key, value);
}
get x() {
return this.x;
}
set x(x) {
this.x = x;
}
get y() {
return this.y;
}
set y(y) {
this.y = y;
}
2019-03-17 23:45:48 -05:00
}
export class Positioned extends decorate(PositionedBase) {}