如何检测框内是否发生了点击

时间:2013-12-30 23:13:36

标签: java lwjgl

当我点击它时,我正试图用鼠标移动一个盒子,然后当我点击它时它停止跟着我的鼠标

代码:

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();
}

一切正常,除非我点击没有任何反应;没有箱子移动。如果我更换

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(0) && **!shape.inBounds(Mouse.getX()** - WINDOW_WIDTH, Mouse.getY() - WINDOW_HEIGHT) && !selected)
{
    selected = true;
    shape.selected = true;
    System.out.println("CLicked meh");
}

(星号,所以你可以看到变化)

我只能移动一个方格,即使点击它也不会移动它。

提前致谢。

1 个答案:

答案 0 :(得分:0)

检查点是否在矩形内的方法实际上是检查点是否在矩形之外。以下内容应返回预期值:

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