java - 查找我的鼠标是否在Java中的矩形内

标签 java slick2d

我开始开发游戏,我需要能够查看我的鼠标是否在矩形内, 我试过将 .contains 用于矩形,但我似乎无法让它工作,我将在下面粘贴我的代码,任何帮助将不胜感激! :)

public boolean isMouseOver(GameContainer gc){
    r = new Rectangle(getX(), getY(),getWidth(),getHeight());
    Input input = gc.getInput();
    xpos = input.getMouseX();
    ypos = input.getMouseY();
    return r.contains(xpos, ypos);
}

这是我尝试使用的方法,但是当鼠标在矩形内时它一直返回 false。显然,我进一步启动了 xpos、ypos 和矩形,并在我尝试使用它的类的更新方法中调用了该方法。

最佳答案

您的鼠标有两个点,分别是 x 和 y 位置。

int mouseX = gc.getInput().getMouseX();
int mouseY = gc.getInput().getMouseY();

我们有一个矩形

Rectangle rec = new Rectangle( 100, 100, 200, 200 );

所以我们可以检查

if ( mouseX >= rec.getMinX() && mouseX <= rec.getMaxX )   // check if X is within range
   && ( mouseY >= rec.getMinY() && mouseY <= rec.getMaxY) // check if y is within range

或者现在我们知道我们的 X 值必须大于矩形的低值但小于它的高值,对于 Y 也是如此让我们检查包含函数

包含(float xp, float yp, float xr, float yr, float widthr, float hightr)

xp - The x coordinate of the point to check
yp - The y coordinate of the point to check
xr - The x coordinate of the rectangle
yr - The y coordinate of the rectangle
widthr - The width of the rectangle
heightr - The height of the rectangle

我想说

包含(mouseX、mouseY、rec.getMinX()、rect.getMinY()、rec.getWidth()、rec.getHeight() )

也许这里出了什么问题?

关于java - 查找我的鼠标是否在Java中的矩形内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17238502/

相关文章:

java - 尝试运行时出错 : NoSuchMethodError: main

java - LRU 在 Java 中快速实现的最佳方式

java - Slick2d |实体碰撞检测

java - 如何在 Java 中延迟一张图像在屏幕上的显示?

java - LWJGL允许负鼠标坐标(窗口外)

java - 如何检测 Slick2D 中旋转图像上的点击?

java - Maven:如何添加修补的依赖项

java - Spring Boot 嵌入式 Tomcat 中的自定义 SAML 身份验证阀 - 不适用于执行器端点

java - 西塔有什么作用?

java - Google 推送通知 - 未经授权的 WebHook 回调 channel