diff --git a/packages/core/src/Entity.ts b/packages/core/src/Entity.ts index baf05acd50..5fcab9b7fc 100644 --- a/packages/core/src/Entity.ts +++ b/packages/core/src/Entity.ts @@ -142,9 +142,7 @@ export class Entity extends EngineObject { throw `The entity ${this.name} is not in the hierarchy`; } - if (this._siblingIndex !== value) { - this._setSiblingIndex(this._isRoot ? this._scene._rootEntities : this._parent._children, value); - } + this._setSiblingIndex(this._isRoot ? this._scene._rootEntities : this._parent._children, value); } /** @@ -568,22 +566,24 @@ export class Entity extends EngineObject { } private _setSiblingIndex(sibling: Entity[], target: number): void { - if (target < 0 || target > sibling.length) { - throw `The index ${target} is out of child list bounds ${sibling.length}`; - } - - const oldIndex = this._siblingIndex; - if (target < oldIndex) { - for (let i = oldIndex; i >= target; i--) { - const child = i == target ? this : sibling[i - 1]; - sibling[i] = child; - child._siblingIndex = i; - } - } else { - for (let i = oldIndex; i <= target; i++) { - const child = i == target ? this : sibling[i + 1]; - sibling[i] = child; - child._siblingIndex = i; + target = Math.min(target, sibling.length - 1); + if (target < 0) { + throw `Sibling index ${target} should large than 0`; + } + if (this._siblingIndex !== target) { + const oldIndex = this._siblingIndex; + if (target < oldIndex) { + for (let i = oldIndex; i >= target; i--) { + const child = i == target ? this : sibling[i - 1]; + sibling[i] = child; + child._siblingIndex = i; + } + } else { + for (let i = oldIndex; i <= target; i++) { + const child = i == target ? this : sibling[i + 1]; + sibling[i] = child; + child._siblingIndex = i; + } } } } diff --git a/tests/src/core/Entity.test.ts b/tests/src/core/Entity.test.ts index a16e045d3b..f8ba90fcea 100644 --- a/tests/src/core/Entity.test.ts +++ b/tests/src/core/Entity.test.ts @@ -351,12 +351,17 @@ describe("Entity", () => { expect(child2.siblingIndex).eq(2); expect(child1.siblingIndex).eq(-1); - // out of range + // project large index + child2.siblingIndex = 5; + expect(child2.siblingIndex).eq(2); + + // thorw error whenless than 0 index var siblingIndexBadFn = function () { - child2.siblingIndex = 5; + child2.siblingIndex = -1; }; expect(siblingIndexBadFn).to.throw(); + // thorw error when set lonely entity const entityX = new Entity(engine, "entityX"); var lonelyBadFn = function () { entityX.siblingIndex = 1;