refactor: sort containers by index if zIndex is equivalent (stable)

This commit is contained in:
cha0s 2019-03-24 04:04:39 -05:00
parent 92f4f4a2d1
commit fe229de317

View File

@ -7,6 +7,7 @@ export class Container extends Renderable {
constructor() {
super();
this._children = [];
this._childrenIndexes = new Map();
this._isDirty = false;
this.internal = PIXI ? new PIXI.Container() : undefined;
}
@ -14,7 +15,8 @@ export class Container extends Renderable {
addChild(child) {
child.parent = this;
this.isDirty = true;
this._children.push(child);
const index = this._children.push(child) - 1;
this._childrenIndexes.set(child, index);
this.internal.addChild(child.internal);
}
@ -40,7 +42,7 @@ export class Container extends Renderable {
this._isDirty = isDirty;
}
removeChild(child) {
_removeChild(child) {
const index = this._children.indexOf(child);
if (-1 === index) {
return;
@ -48,11 +50,20 @@ export class Container extends Renderable {
this._children.splice(index, 1);
this.internal.removeChild(child.internal);
}
removeChild(child) {
this._removeChild(child);
this._childrenIndexes = new Map();
for (const i in this._children) {
const child = this._children[i];
this._childrenIndexes.set(child, i);
}
}
removeAllChildren() {
for (const child of this._children) {
this.removeChild(child);
this._removeChild(child);
}
this._childrenIndexes = new Map();
}
tick() {
@ -72,7 +83,12 @@ export class Container extends Renderable {
return;
}
this._children.sort((l, r) => {
return l.zIndex - r.zIndex;
if (l.zIndex !== r.zIndex) {
return l.zIndex - r.zIndex;
}
const lIndex = this._childrenIndexes.get(l);
const rIndex = this._childrenIndexes.get(r);
return lIndex - rIndex;
});
this.internal.children = this._children.map((child) => {
return child.internal;