refactor: room world property

This commit is contained in:
cha0s 2019-03-27 16:11:37 -05:00
parent e50f4e9f1a
commit 71ff55c1a7
2 changed files with 34 additions and 13 deletions

View File

@ -45,6 +45,12 @@ export class Physical extends decorate(Trait) {
}
set world(world) {
if (this._world) {
this._world.removeBody(this._body);
}
if (this.bodyView) {
this.bodyView.destroy();
}
this._world = world;
if (world) {
const body = world.createBody(this.entity.shape);

View File

@ -1,12 +1,15 @@
import * as I from 'immutable';
import {compose} from '@avocado/core';
import {EventEmitter} from '@avocado/mixins';
import {EventEmitter, Property} from '@avocado/mixins';
import {Layers} from './layers';
const decorate = compose(
EventEmitter,
Property('world', {
track: true,
}),
);
class RoomBase {
@ -14,7 +17,6 @@ class RoomBase {
constructor() {
this.layers = new Layers();
this._state = I.Map();
this._world = undefined;
// Listeners.
this.onEntityAddedToRoom = this.onEntityAddedToRoom.bind(this);
this.onEntityRemovedFromRoom = this.onEntityRemovedFromRoom.bind(this);
@ -34,6 +36,9 @@ class RoomBase {
destroy() {
this.layers.destroy();
this.layers.off('entityAdded', this.onEntityAddedToRoom);
this.layers.off('entityRemoved', this.onEntityRemovedFromRoom);
this.off('worldChanged', this.onWorldChanged);
}
fromJSON(json) {
@ -56,6 +61,16 @@ class RoomBase {
this.emit('entityRemoved', entity);
}
onWorldChanged() {
for (const layer of this.layers) {
for (const entity of layer.entityList) {
if (entity.is('physical')) {
entity.world = this.world;
}
}
}
}
removeEntityFromLayer(entity, layerIndex = 0) {
this.layers.removeEntityFromLayer(entity, layerIndex);
}
@ -67,19 +82,19 @@ class RoomBase {
tick(elapsed) {
this.layers.tick(elapsed);
this._state = this._state.set('layers', this.layers.state);
if (this._world) {
this._world.tick(elapsed);
if (this.world) {
this.world.tick(elapsed);
}
}
get world() {
return this._world;
}
set world(world) {
this._world = world;
}
}
export class Room extends decorate(RoomBase) {}
export class Room extends decorate(RoomBase) {
constructor() {
super();
this.onWorldChanged = this.onWorldChanged.bind(this);
this.on('worldChanged', this.onWorldChanged);
}
}