Recent Comments

Archives

Categories

Meta

Drag and Drop Inventory with LibGDX (Part II)

In this part II of our inventory tutorial series we are going to create the actual UI for our Inventory and Slots. LibGDX offers us some basic functionality for UIs, namely scene2d.ui. In case you are not familiar with it yet, you should probably read this article first.

The SlotActor

In part I of this series, we have seen how a Slot looks like. Now we have to render this slot somehow. To do so, we are going to create a SlotActor which is an ImageButton itself, and which displays the TextureRegion of the Item.

As always, read the code carefully and also check the comments within. It should be pretty self-explanatory.

The InventoryActor

To display the Inventory, we are going to create a new Window which can be dragged around by default. For each Slot of the Inventory, we are going to create a new SlotActor, which we’ve just seen in the previous paragraph.

public class InventoryActor extends Window {
public InventoryActor(Inventory inventory, DragAndDrop dragAndDrop, Skin skin) {
super("Inventory", skin);
// add an "X" button to the top right of the window, and make it hide the inventory
TextButton closeButton = new TextButton("X", skin);
closeButton.addListener(new HidingClickListener(this));
getButtonTable().add(closeButton).height(getPadTop());
// basic layout
setPosition(400, 100);
defaults().space(8);
row().fill().expandX();
// run through all slots and create SlotActors for each
int i = 0;
for (Slot slot : inventory.getSlots()) {
SlotActor slotActor = new SlotActor(skin, slot);
add(slotActor);
// this can be ignored for now and will be explained in part III
dragAndDrop.addSource(new SlotSource(slotActor));
dragAndDrop.addTarget(new SlotTarget(slotActor));
i++;
// every 5 cells, we are going to jump to a new row
if (i % 5 == 0) {
row();
}
}
pack();
// it is hidden by default
setVisible(false);
}
}

Closing the inventory

This is actually pretty easy. In the previous code you could already see that we added a HidingClickListener to the button to close the window. Its only purpose is to hide a given actor on click.

Next

In this part, we have created a basic UI for our inventory and slots. But we cannot do much with it yet. In the next part we will see how to make that inventory interactive by adding drag and drop functionality!