Search code examples
javalwjgl

How to detect if a click has happened inside a box


I'm trying to make a box move around with my mouse when I click it, then when I right click it stops following my mouse

Code:

boolean inBounds(int mouseX, int mouseY)
{
    if (mouseX <= x && mouseX >= x + width && mouseY <= y && mouseY >= y + height)
        return true;
    else
        return false;
}

private List<Box> shapes = new ArrayList<Box>(60);

for (Box shape : shapes)
{
    if (Mouse.isButtonDown(0) && shape.inBounds(Mouse.getX() - WINDOW_WIDTH, Mouse.getY() - WINDOW_HEIGHT) && !selected)
    {
        selected = true;
        shape.selected = true;
        System.out.println("CLicked meh");
    }
    if (Mouse.isButtonDown(1))
    {
        shape.selected = false;
        selected = false;
    }

    if (shape.selected)
    {
        shape.Update(Mouse.getDX(), -Mouse.getDY());
    }

    shape.Draw();
}

Everything works fine, except when I click nothing happens; no boxes moved. If I replace

if (Mouse.isButtonDown(0) && shape.inBounds(Mouse.getX() - WINDOW_WIDTH, Mouse.getY() - WINDOW_HEIGHT) && !selected)
{
    selected = true;
    shape.selected = true;
    System.out.println("CLicked meh");
}

with this

if (Mouse.isButtonDown(0) && **!shape.inBounds(Mouse.getX()** - WINDOW_WIDTH, Mouse.getY() - WINDOW_HEIGHT) && !selected)
{
    selected = true;
    shape.selected = true;
    System.out.println("CLicked meh");
}

(Asterisks so you can see changes)

I can only move one square, and not even while clicking on it, clicking anywhere moves it.

Thanks in advance.


Solution

  • Your method for checking if the point is within the rectangle is actually checking if the point is outside of the rectangle. The following should return the expected value:

    boolean inBounds(int mouseX, int mouseY) {
        return ((mouseX >= x) && (mouseY >= y) && (mouseX < x + width) && (mouseY < y + height));
    }