Search code examples
javauser-interfacelibgdxinventoryscene2d

How do I make an actor move to the foreground temporarily in LibGDX scene2d?


I have an inventory UI which is a table in scene2d. Then the table had a bunch of Containers which are basically inventory slots. They have a transparant grey background color. Then in each container is an ItemStack with a picture of an item and a stacksize. When I pull this ItemStack over a container that was created later, it moves behind the container and the transparant grey background will be in front of the item picture. How do I temporarily (or permanently) move it to the foreground so it doesn't matter in front of which container I drag the item?

Example of what happens: https://i.imgur.com/yq4njex.gifv

This is how I create the containers:

// Create inventory slots
table.row();
inventorySlots.clear();
for (int i = 0; i < inventory.getInventorySize(); i++) {
    if (i % SLOTS_PER_ROW == 0) table.row();

    Container cont = new Container();
    cont.fill();
    cont.background(Utils.createDrawable(1, 1, new Color(0, 0, 0, 0.4f)));

    inventorySlots.add(cont);
    table.add(cont).prefHeight(50).prefWidth(50).pad(5);
}

After that I add each ItemStack to the list of containers/inventoryslots like this:

// Add ItemStacks from Items to their respective slot
ArrayList<Item> items = inventory.getItems();
for(Container slot : inventorySlots) {
    Item item = items.get(inventorySlots.indexOf(slot));

    if(item != null) {
        ItemStack itemStack = new ItemStack(item);
        addInventoryEvent(itemStack, items);
        slot.pad(5);
        slot.setActor(itemStack);
    }
}

Solution

  • You can use Actor.setZindex() to move the actor you are dragging to front.

    Sets the z-index of this actor. The z-index is the index into the parent's children, where a lower index is below a higher index. Setting a z-index higher than the number of children will move the child to the front. Setting a z-index less than zero is invalid

    A solution might be

    image.addListener(new InputListener(){
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            image.setZIndex(stage.getActors().size);
            return true;
        }
    });
    

    enter image description here