gpt4 book ai didi

java - 检查 2 个矩形是否会重叠

转载 作者:行者123 更新时间:2023-12-02 04:42:39 25 4
gpt4 key购买 nike

我一直在尝试让玩家与我正在做的一个小项目相交,但我似乎无法让它发挥作用。我让交叉点与玩家和墙壁一起工作,但它非常有缺陷,我的意思是,它会将玩家吸引到墙上,然后立即将他移回来。 (查看 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

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

P.S:出于测试目的,我现在只能进入 1 个盒子。

最佳答案

您可以移动玩家,然后检查它是否在墙上,如果是,则撤消移动(或者更好的是,计算一个新位置作为移动的结果,检查它,如果它是好的,然后才将玩家移动到那里)。请注意,这假设单次移动无法将您一直带到墙的另一侧,但看起来您的代码也能做到这一点。

关于java - 检查 2 个矩形是否会重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30010515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com