Question

Im working on a card game using libgdx and scene2d. My card class extends the Image actor class. Im trying to find a way to set the order of how my cards are drawn based on their x position when dragged.

enter image description here

So i tried:

@Override
public void drag(InputEvent event, float x, float y, int pointer) {
     float sx = event.getStageX();
     float sy = event.getStageY();
     if(sx - offsetX > 0 && sy - offsetY > 0){
       event.getTarget().setPosition(sx - offsetX, sy - offsetY);
       c.setZIndex((int) sx);
    }               
}

This wont work because apparently, the zindex is bound to the number of actors in the stage/group. So basically the index should be 0-4. My next approach was to divide the screen width by 5 and set that to the zindex. It works fine if the cards are separated evenly across the whole width. But if the cards are compressed in the middle, they dont look good. 2 to 3 cards fall in the middle, and the last dragged one is the one drawn on top of the others. Which i dont want.

My last approach was to order all my cards by their xposition and loop through them giving z-index. And this works like i want but i find it slow (when all the other stuff are added in the mix)

So is there anyway i can set z-index relative to x-position without looping through the actors?

Was it helpful?

Solution

Have an array of initial positions of all your cards. Whenever drag happens, re-shuffle your array based from the drag method you already have. Draw the cards using the positions stored in your array from 0 to length - 1 where first card's position is at index 0 and the last one is at length of array minus 1.

Or - use Group. Add group in draw order. You can swap actors in a group. Swap the cards based from drag events.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top