Java,LibGDX,矩形相交失败,维数为负?
我正在用Java和LibGDX制作一个用于RTS游戏的单元选择器。我创建了一个矩形来检查units hitbox是否与所选内容的hitbox冲突,如果冲突,则将该单位添加到所选单位的列表中
如果我在一个方向上拖动鼠标,则在另一个方向上选择单位(当创建宽度/高度为负的矩形时,它们不会被选中)。你对为什么会这样有什么建议吗
谢谢
选择器代码:
boolean selectInProg = false;
public List<Entity> createSelection(List<Entity> entities){
if(Gdx.input.isButtonPressed(Input.Buttons.LEFT)){
if(!selectInProg){
xDown = Gdx.input.getX();
yDown = Gdx.graphics.getHeight() - Gdx.input.getY();
selectInProg = true;
}
hitbox.set(xDown, yDown, Gdx.input.getX() - xDown, (Gdx.graphics.getHeight() - Gdx.input.getY()) - yDown);
}else{
hitbox = new Rectangle();
selectInProg = false;
}
List<Entity> selected = new ArrayList();
for(Entity entity : entities){
if(Intersector.intersectRectangles(hitbox, entity.hitbox, new Rectangle())){
selected.add(entity);
entity.selected = true;
}
}
return selected;
}
# 1 楼答案
取自here和here,这是因为
Rectangle.overlaps
:此代码假定矩形的宽度/高度具有相同的符号。因此,如果
x
描述了两个矩形的左侧或右侧,它就起作用了。当然,这同样适用于y
。但是,如果x
描述了矩形1的右侧和矩形2的左侧,则它不起作用我建议您只需构造矩形来覆盖
overlaps
:然后重要的是将
hitbox
作为第一个参数传递给Intersector.intersectRectangles
,但您已经这样做了当然,如果你更喜欢这些,你也可以用一行代码来支持上面的内容: