Handle mouse hovering in the screen.

Hi!

I’ve recently implement the inventory for my game wich shows in the screen a simple rect partitioned in 32 subrects showing all the items in characters inv. http://puu.sh/mZny

I’d like to know how can i handle the mouse hovering of every item in the inventory to make the mouse listener work.

I mean, when hovering an item, right clicking will use/equip it and left clicking will able it to drag/drop it.

Thanks for help!

PS: I don’t need code, just knowledge about how to do it :slight_smile:

What exactly don’t you know how to do? This sounds like a basic mouse click/motion event problem.

[quote]Zengoku’s avatar
[/quote]
Ka… Kawaii… OMOCHIKAERIII!!!

I think what you’re missing is a MouseMotionListener.

If you let a class ‘implement’ a ‘MouseMotionListener’, you than have access to methods like:


	// Anytime the mouse is moved we assign its X,Y.
	public void mouseMoved(MouseEvent e) { }

	// When the mouse leaves the screen.
	public void mouseExited(MouseEvent e) { }

	// When the mouse is inside of the screen.
	public void mouseEntered(MouseEvent e) { }

Here’s a simple way of assigning a int to a rectangle, than creating a boolean to detect if the mouse’s inside of the given rectangle’s coordinates.


public int mouseX, mouseY = 0;

		// So if the mouse is inside of this 40x40 rectangle at 40X, 40Y, return = true;
	public boolean mouseInSlot(int slot) {
		int x = mouseX;
		int y = mouseY;
		if (x > 40 && x < 80 && y > 40 && y < 80) {
			return true;
		} else {
			return false;
		}
	}

	// Anytime the mouse is moved we assign its X,Y.
	public void mouseMoved(MouseEvent e) {
		mouseX = e.getX();
		mouseY = e.getY();
	}

Sorry for posting code >:( hope it helps.

Don’t do this. Calculate which slot the mouse is over instead.


public int getHoveredSlot(int x, int y){
    if(!isInsideInventoryWindow(x, y)){
        return -1; //Outside window, no slot
    }
    return ((y - inventoryWindowY) / SLOT_HEIGHT) * INVENTORY_COLUMNS + (x - inventoryWindowX) / SLOT_WIDTH;
    //Example: window location = (0, 0), slot size = (10, 10), columns = 10, mouse position = (15, 15) = center of second row, second column = slot coordinates (1, 1) (starts at 0) = index 11.
    //((15 - 0) / 10) * 10 = ((15)/10)*10 = 1*10 = 10 (note the rounding) 
    // +
    // (15 - 0) / 10 = 15/10 = 1
    // =
    // 11
}

Its efficient, but OP has gaps between the inventory slots

Aw, damn. I guess we’ll just have to give up then. It’s not like we’re programmers who can just add an additional check to ensure we didn’t hit the space between slots after using the method I posted… :wink:

Unless space is really big you can ignore it ;D

Hah, sorry, i tend to get obvious sometimes :stuck_out_tongue: