如何检测Java中哪一侧被Rectangle命中

时间:2015-12-03 21:38:54

标签: java java-8 collision-detection game-physics rectangles

我正在用Java开发一个Breakout游戏,我已经到了能够检测到Brick的哪一侧被Ball交叉的地步。目前我正在使用intersects方法,但是这仅检测交叉点,而不是特定于哪一侧被击中。这是方法(我在一些评论中添加了):

public boolean intersects(Rectangle r) {
    // The width of the Brick as tw
    int tw = this.width;
    // The height of the Brick as th
    int th = this.height;
    // The width of the given Rectangle as rw
    int rw = r.width;
    // The height of the given Rectangle as rh
    int rh = r.height;
    // Check if the given Rectangle or Brick does not exist
    if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {

        // If not, then return false because there is nothing to collide/intersect
        return false;
    }

    // The x location of Brick as tx
    int tx = this.brickLocation.x;
    // The y location of Brick as ty
    int ty = this.brickLocation.y;
    // The x location of the given Rectangle as rx
    int rx = r.x;
    // The y location of the given Rectangle as ry
    int ry = r.y;

    // RW = RW + RX
    rw += rx;
    // RH = RH + RY
    rh += ry;
    // TW = TW + TX
    tw += tx;
    // TH = TH + TY
    th += ty;

    //      overflow || intersect
    return ((rw < rx || rw > tx) &&
            (rh < ry || rh > ty) &&
            (tw < tx || tw > rx) &&
            (th < ty || th > ry));
}

我现在已经把这个方法放到了我的一个类中,我正在定制它,但是我在制作它时遇到了麻烦,因此它检测到哪一方被击中,因为最终的返回语句只是如此相互关联,你可以'只需要取其中一条线,因为为了让它知道那边的结束,它需要知道其他边,这就是它在这里所做的,如果它已经与所有边相交(并且没有限制在双方的外展 - 虽然当然可见它们是有限的)然后它返回真实,如果不是那么没有,它没有触及形状,因为否则它会完成。

我希望能够做到这一点,以便有if语句决定返回什么int(我将它的返回类型从boolean更改为int),因此它已经命中了哪一侧它可以以适当的方式反弹。但由于这些是如此相互依赖,我不知道如何将它们分开:

    //      overflow || intersect
    return ((rw < rx || rw > tx) &&
            (rh < ry || rh > ty) &&
            (tw < tx || tw > rx) &&
            (th < ty || th > ry));

我在这里看过很多类似的问题,但要么是用不同的语言,没有任何答案,要么没有任何答案可以回答问题而已被接受。所以我想知道是否有人可以向我建议我如何将它们分开以便它能够检测到哪一方被击中,因为我没有想法?
或者也许已经有一种Java方法可以为我做这个并且我不必覆盖已经存在的方法?我有最新版本的Oracle JDK 8。

2 个答案:

答案 0 :(得分:1)

你能做到的一种方法就是在移动球时我假设你做了这样的事情:

ball.x += speedX;
ball.y += speedY;

您可以将其转为:

ball.x += speedX;
if (intersects(ball, brick))
{
    //Ball touched brick on left/right side (depending if speedX is positive or negative)
}
ball.y += speedY;
if (intersects(ball, brick))
{
    //Ball touched brick on top/bottom side (depending if speedY is positive or negative)
}

答案 1 :(得分:0)

尝试让你的相交(矩形r)函数在没有击中任何一侧的情况下返回-1,并且0-1-2-3确定你击中的一侧。根据什么部分增加..