我在平铺游戏中工作。我想检查平铺器离开播放器的方向,何时发生碰撞。
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;
}
如果没有碰撞,我希望此函数返回0
1 = rect1在左边
2 = rect1在右边
3 = rect1位于底部
4 = rect1位于顶部
喜欢这张照片:
我试过这个
// 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;
}
但是不起作用..
答案 0 :(得分:1)
这假定左下角原点坐标系(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));
}