检查 2 个矩形是否会重叠

checking if 2 rectangles WILL overlap

我一直在尝试与我正在做的一个小项目进行玩家交集,但我似乎无法让它发挥作用。我让 Intersection 与玩家和墙一起工作,但它有很多错误,我的意思是错误,它将玩家吸引到墙上然后立即将他移回。 (检查 Gyazo 以获得 gif)。我很确定问题是它只检查玩家是否在墙上,而不是在墙上,但我似乎无法弄清楚如何检查这个。这是我目前所拥有的:

public void intersectsBox2(Rectangle r, Rectangle r2) {
    P1 = new Point((int) r.getMinX(), (int) r.getMinY());
    P2 = new Point((int) r.getMaxX(), (int) r.getMaxY());
    P3 = new Point((int) r2.getMinX(), (int) r2.getMinY());
    P4 = new Point((int) r2.getMaxX(), (int) r2.getMaxY());
    if ((P2.y < P3.y || P1.y > P4.y || P2.x < P3.x || P1.x > P4.x)
            && !intersectsBox(playerRectangle(), noWalls[0])) {
        isInsideWalls = true;
    }
}

// Gets the players rectangle
public Rectangle playerRectangle() {
    return new Rectangle(9 + dx, 23 + dy, 54, 90);
}

这是为了让玩家移动:

public void playerMovement() {
    if (isInsideWalls) {
        System.out.println("YOU ARE IN THE BOX!");
        if (animation == down) {
            dy -= moveSpeed;
            isInsideWalls = false;
        } else if (animation == up) {
            dy += moveSpeed;
            isInsideWalls = false;
        } else if (animation == left) {
            dx += moveSpeed;
            isInsideWalls = false;
        } else if (animation == right) {
            dx -= moveSpeed;
            isInsideWalls = false;
        }
    } else {
        // Moves the player
        if (moving == downMove) {
            dy += moveSpeed;
            moving = 0;
        } else if (moving == upMove) {
            dy -= moveSpeed;
            moving = 0;
        } else if (moving == leftMove) {
            dx -= moveSpeed;
            moving = 0;
        } else if (moving == rightMove) {
            dx += moveSpeed;
            moving = 0;
        }
    }

这是为了检查交集:

//Checks for intersection
for (int i = 0; i < 9; i++) {
    for (int j = 0; j < 9; j++) {
        intersectsBox2(walls[i][j], playerRectangle());
    }
}

不太确定是否需要这个,但如果您需要查看,这里是完整的Game.java:http://pastebin.com/GrDy689d

这里还有问题的动图:http://i.gyazo.com/1f31f739897af78f81e61cf22ac772db.mp4

P.S: 故意的 我现在只能进1个箱子做测试

您可以移动播放器,然后检查它是否在墙上,如果是,则撤消移动(或者更好的是,计算一个新位置作为移动的结果,检查它,如果它是好的,然后才将玩家移动到那里)。请注意,这是假设一个单一的移动不能让你一直走到墙的另一边,但看起来你的代码也是如此。