refactor: trait packet helpers

This commit is contained in:
cha0s 2019-05-14 05:45:22 -05:00
parent d0ae543ae4
commit cbc2401f27
4 changed files with 28 additions and 27 deletions

View File

@ -27,6 +27,15 @@ export class Trait extends decorate(class {}) {
}
}
createTraitPacketUpdates(Packet) {
const packets = [];
if (this.isDirty) {
packets.push(new Packet(this.state, this.entity));
this.makeClean();
}
return packets;
}
destroy() {}
hooks() {
@ -37,6 +46,15 @@ export class Trait extends decorate(class {}) {
return Promise.resolve();
}
get isDirty() {
for (const key in this.state) {
if (this.state[key] !== this.previousState[key]) {
return true;
}
}
return false;
}
label() {
return this.constructor.name;
}
@ -45,6 +63,12 @@ export class Trait extends decorate(class {}) {
return {};
}
makeClean() {
for (const key in this.state) {
this.previousState[key] = this.state[key];
}
}
memoizedListeners() {
if (!this._memoizedListeners) {
this._memoizedListeners = this.listeners();

View File

@ -41,14 +41,7 @@ export class Directional extends decorate(Trait) {
}
packetsForUpdate() {
const packets = [];
if (this.state.direction !== this.previousState.direction) {
packets.push(new TraitDirectionalPacket({
direction: this.state.direction,
}, this.entity));
this.previousState.direction = this.state.direction;
}
return packets;
return this.createTraitPacketUpdates(TraitDirectionalPacket);
}
listeners() {

View File

@ -74,10 +74,7 @@ export class Positioned extends decorate(Trait) {
packetsForUpdate() {
const packets = [];
if (
this.state.x !== this.previousState.x
|| this.state.y !== this.previousState.y
) {
if (this.isDirty) {
// Physics slop can end us up with negatives. Don't allow them in the
// packed representation, even though it means a slight loss in accuracy.
// The world bounds will (should!) keep things *eventually* correct.
@ -87,8 +84,7 @@ export class Positioned extends decorate(Trait) {
packets.push(new TraitPositionedPacket({
position: packed,
}, this.entity));
this.previousState.x = this.state.x;
this.previousState.y = this.state.y;
this.makeClean();
}
return packets;
}

View File

@ -151,19 +151,7 @@ export class Animated extends decorate(Trait) {
}
packetsForUpdate() {
const packets = [];
if (
this.state.currentAnimation !== this.previousState.currentAnimation
|| this.state.isAnimating !== this.previousState.isAnimating
) {
packets.push(new TraitAnimatedPacket({
currentAnimation: this.state.currentAnimation,
isAnimating: this.state.isAnimating,
}, this.entity));
this.previousState.currentAnimation = this.state.currentAnimation;
this.previousState.isAnimating = this.state.isAnimating;
}
return packets;
return this.createTraitPacketUpdates(TraitAnimatedPacket);
}
setSpriteScale() {