有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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;

}

Arrow shows mouse movement during selection, on the left the entities are selected. On the right they are not.


共 (1) 个答案

  1. # 1 楼答案

    取自herehere,这是因为Rectangle.overlaps

    public boolean overlaps (Rectangle r) {
        return x < r.x + r.width && x + width > r.x && y < r.y + r.height && y + height > r.y;
    }
    

    此代码假定矩形的宽度/高度具有相同的符号。因此,如果x描述了两个矩形的左侧或右侧,它就起作用了。当然,这同样适用于y。但是,如果x描述了矩形1的右侧和矩形2的左侧,则它不起作用

    我建议您只需构造矩形来覆盖overlaps

    hitbox = new Rectangle(){
        public boolean overlaps (Rectangle r) {
            float left = Math.min(x, x + width);
            float right = Math.max(x, x + width);
            float top = Math.min(y, y + height);
            float bottom = Math.max(y, y + height);
            float left2 = Math.min(r.x, r.x + r.width);
            float right2 = Math.max(r.x, r.x + r.width);
            float top2 = Math.min(r.y, r.y + r.height);
            float bottom2 = Math.max(r.y, r.y + r.height);
            return left < right2 && right > left2 && top < bottom2 && bottom > top2;
        }
    };
    

    然后重要的是将hitbox作为第一个参数传递给Intersector.intersectRectangles,但您已经这样做了

    当然,如果你更喜欢这些,你也可以用一行代码来支持上面的内容:

    hitbox = new Rectangle(){
        public boolean overlaps (Rectangle r) {
            return Math.min(x, x + width) < Math.max(r.x, r.x + r.width) && Math.max(x, x + width) > Math.min(r.x, r.x + r.width) && Math.min(y, y + height) < Math.max(r.y, r.y + r.height) && Math.max(y, y + height) > Math.min(r.y, r.y + r.height);
        }
    };