【问题标题】:Point and Rectangle collision detection?点和矩形碰撞检测?
【发布时间】:2015-02-28 01:46:27
【问题描述】:

所以我创建了一个方法来检测 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 会随着您向右而增加。为什么这种方法不能检测圆边缘上顶点和底部的交点?此外,屏幕是横向的。

【问题讨论】:

    标签: java android collision-detection


    【解决方案1】:

    看起来这只是一个逻辑错误,我假设 .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;
    }
    

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

    【讨论】:

    • 谢谢你现在它工作得很好,但我必须做两处改变:ball.getY() + ball.getR() &lt;= rect.getTheBottom()ball.getY() + ball.getR() &gt;= rect.getTheTop() 谢谢你!
    • 很高兴你成功了,尝试调试逻辑总是很有趣
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多