have you tried to use an array of Rectangles then use a method like this to draw for example 35 inventory slots going left to right until finished.
public Rectangles[] invSlots;
public int INVENTORY_CELL_SIZE_X = 50;
public int INVENTORY_CELL_SIZE_Y = 50;
public int AMOUNT_OF_INVENTORY_CELLS = 35;
public void createSlots() {
invSlots = new Rectangle[AMOUNT_OF_INVENTORY_CELLS];
for(int id = 0;id < invSlots.length;id++) {
for(int x = 0;x<INVENTORY_CELL_SIZE_X;x+=INVENTORY_CELL_SIZE_X) {
for(int y = 0;y<INVENTORY_CELL_SIZE_Y;y+=INVENTORY_CELL_SIZE_Y) {
//use all incremented integers above to create rectangles transform;
invSlots[id] =
new Rectangle(x, y,INVENTORY_CELL_SIZE_X, INVENTORY_CELL_SIZE_Y);
}
}
}
}
YOU CAN THEN DRAW ONE OF THESE CELLS LIKE SO;You can then draw one of these cells like so;
g.drawImage(image or rect_here,
invSlots[incrementedInteger].x, invSlots[incrementedInteger].y,
invSlots[incrementedInteger].width, invSlots[incrementedInteger].height);
heres how to check what cell the player's mouse is inside of.
MAKE SURE YOU CALL IT FROM WITHIN A LOOPMake sure you call it from within a loop.
public void checkForMouseEntryOrWhatever() {
for(int id = 0;id<invSlots.length;id++) {
//mouse start
if(mouseX >= invSlots[id].x
&& mouseY >= invSlots[id].y
&& mouseX <= invSlots[id].x+invSlots[id].width
&& mouseY <= invSlots[id].y+invSlots[id].height)
{
//DO WHATEVER WHEN THE PLAYER ENTERS THE INVENTORY CELL.
}
//Mouse end
}
}
this method was made to be universal no matter the rectangles size.
it also has a basic id system because of the array, and is organized because of the 'left-to-right' drawing technique.
creating a Item dragging system shouldnt be very difficult after this if your using mouseDragged() method, simply make the item (that the player clicked-to-drag) follow the players mouse until released and then place that item in the slot that it was released in.
try this if statement for example.
it only works inside of a loop (for loop or while loop should do depending on engine)
if(releasedX >= slotX && releasedY >= slotY && releasedX <= slotX +
slotWidth && slotY <= slotY+slotHeight) {
drawItem(item, slotX, slotY, itemWidth, itemHeight);
}