Dennis Robertson
Dennis Robertson

Reputation: 31

Z-Index in KineticJS

I'm trying to program with kineticJS but I got some trouble with the Z-Index management.

It seems you cant just set a z-index of any range you want, but every object gets its own z-index and you can just rechange them with others. So if you got 2 objects, they got z-index of 0 and 1. You cant set it to 100 or something like that. Is that correct?

My problem is, I'm trying to program a small game with an isometric overview. And the player should have a lower z-index then the walls he is walking behing, but a higher z-index when he is infront of the walls. But I cant have all walls of the same y-coordinate have the same z-index, they all get their own z-index that is free, which makes all very random.

For example, the walls at the y-coordinate of 5 got z-index 5, while the player infront of the walls have z-index 6. But at the end, all the walls just get random index of 5-20 and the player gets a random index, making it totally impossible to create such a game.

Is there any other way to manage the z-index of the objects? The only solution I see is to make a hidden layer with 2 hidden objects for all tiles of my map with unique z-index, and programm a script that dynamicly change them with walls and players or other objects. But there has to be a better way to just make sure the objects are displayed in the right order?

Upvotes: 3

Views: 1013

Answers (1)

Richard Kennard
Richard Kennard

Reputation: 1325

I just hit the same issue. It appears Z-index only works sequentially? So I sorted my list of elements and then assigned their Z-index based on the array index:

var sortedElements = _elements.slice();
sortedElements.sort(function(a, b) {
    var diff = a.getY() - b.getY();
    if ( diff !== 0 ) { return diff; }
    return a.getX() - b.getX();
} );
for ( var loop = 0, length = sortedElements.length; loop < length; loop++ ) {
    sortedElements[loop].setZIndex(loop);
}

Upvotes: 1

Related Questions