[英]java - get direction of rectangle collision
I'm working at a tiled game. 我在玩平铺游戏。 I want to check the direction where the tiled is from the player, when is colliding.
我想检查碰撞时播放器平铺的方向。
static public boolean intersectRectangles(Rectangle rectangle1, Rectangle rectangle2, Rectangle intersection) {
if (rectangle1.overlaps(rectangle2)) {
intersection.x = Math.max(rectangle1.x, rectangle2.x);
intersection.width = Math.min(rectangle1.x + rectangle1.width, rectangle2.x + rectangle2.width) - intersection.x;
intersection.y = Math.max(rectangle1.y, rectangle2.y);
intersection.height = Math.min(rectangle1.y + rectangle1.height, rectangle2.y + rectangle2.height) - intersection.y;
return true;
}
return false;
}
I want this function to return 0 if there is no collision 如果没有冲突,我希望此函数返回0
1 = rect1 is in the left 1 = rect1在左侧
2 = rect1 is in the right 2 = rect1在右边
3 = rect1 is in the bottom 3 = rect1在底部
4 = rect1 is in the top 4 = rect1在顶部
Like this pic: 像这张照片:
I tried doing this 我尝试这样做
// if there is a collision between player and tile
float xdif = player.x + 40 - j * 40;
float ydif = player.y + 40 - i * 40;
Direction direction = Direction.RIGHT;
if (Math.abs(xdif) > Math.abs(ydif)) {
if (player.y > i * 40)
direction = Direction.DOWN;
else
direction = direction.UP;
} else {
if (player.x > j * 40)
direction = Direction.LEFT;
else
direction = direction.RIGHT;
}
But is not working.. 但是没有用..
This assumes a bottom-left origin coordinate system (x→, y↑) 假设左下角的原点坐标系(x→,y↑)
static public int intersectRectangles(Rectangle player, Rectangle tile) {
if(!player.overlaps(tile))
return 0;
Double pL = player.x, //left
pR = pL + player.width, //right
pT = player.y, //bottom
pB = pT + player.height; //top
Double tL = tile.x, //left
tR = tL + tile.width, //right
tT = tile.y, //bottom
tB = tT + tile.height; //top
Double inf = Double.MAX_VALUE;
List<Double> intersect_diffs = new ArrayList<Double>(new Double[] {inf,inf,inf,inf});
if(pR > tL && pL < tL) // Player on left
intersect_diffs[0] = pR - tL;
if(pL < tR && pR > tR) // Player on Right
intersect_diffs[1] = tR - pL;
if(pT > tB && pB < tB) // Player on Bottom
intersect_diffs[2] = pT - tB;
if(pB < tT && pT > tT) // Player on Top
intersect_diffs[3] = tT - pB;
// return the closest intersection
return intersect_diffs.indexOf(Collections.Min(intersect_diffs));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.