点和矩形碰撞检测?

时间:2015-02-28 01:46:27

标签: java android collision-detection

所以我创建了一个方法来检测BallView球和Rectangle矩形之间的碰撞。我把它分成了4个部分;它可以检测到圆的最顶部,圆的最左边,圆的最底部,圆的最右边和矩形之间的碰撞。其中两项工作是检测圆上的左点与矩形之间的碰撞,并检测圆上的右点与矩形之间的碰撞。但是,无法工作的是,如果最顶点或最底点触摸矩形,则没有检测到碰撞,因为当我记录if语句以查看是否输入时我可以看到。这是我的代码(方法.getR()得到圆圈半径):

public boolean intersects(BallView ball, Rectangle rect){
    boolean intersects = false;

    //Left point
    if (ball.getX() - ball.getR() >= rect.getTheLeft() &&
        ball.getX() - ball.getR()<= rect.getTheRight() &&
        ball.getY() <= rect.getTheBottom() &&
        ball.getY() >= rect.getTheTop())
    {
        intersects = true;
    }

    //Right point
    if (ball.getX() + ball.getR() >= rect.getTheLeft() &&
        ball.getX() + ball.getR() <= rect.getTheRight() &&
        ball.getY() <= rect.getTheBottom() &&
        ball.getY() >= rect.getTheTop())
    {
        intersects = true;
    }

    //Bottom point (wont work?)
    if (ball.getX() >= rect.getTheLeft() &&
        ball.getX() <= rect.getTheRight() &&
        ball.getY() + ball.getR() <= rect.getTheBottom() &&
        ball.getY() + ball.getR()>= rect.getTheTop())
    {
        intersects = true;
    }

    //Top point (wont work?)
    if (ball.getX() >= rect.getTheLeft() &&
        ball.getX() <= rect.getTheRight() &&
        ball.getY() - ball.getR()<= rect.getTheBottom() &&
        ball.getY() - ball.getR()>= rect.getTheTop())
    {
        intersects = true;
    }

    return intersects;

}

我已经考虑到,当你走下去时,Y会增加,而当你走右时,X会增加。为什么这种方法不会检测圆圈边缘顶点和底点的交点?此外,屏幕面向风景。

1 个答案:

答案 0 :(得分:0)

看起来它只是一个逻辑错误,我假设.getX和.getY是球中心的x和y坐标,以及.getR是半径,所以你想要你的代码看起来像这样

if (ball.getX() + ball.getR() >= rect.getTheLeft() &&
    ball.getX() - ball.getR() <= rect.getTheRight() &&
    ball.getY() - ball.getR() <= rect.getTheBottom() &&
    ball.getY() + ball.getR() >= rect.getTheTop())
{
    intersects = true;
}

我不确定您应用的具体细节,但我不确定您是否需要更多信息来判断球是否与矩形相交