我开始开发游戏,我需要能够查看我的鼠标是否在矩形内, 我试过将 .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/