1

使用以下代码,可以检测到碰撞,但边注册不正确。

public int checkBoxes(int aX, int aY, int aWidth, int aHeight, int bX, int bY, int bWidth, int bHeight){

    /*
     * Returns int
     * 0 - No collisions
     * 1 - Top
     * 2 - Left
     * 3 - Bottom
     * 4 - Right
     */

    Vector2f aMin = new Vector2f(aX, aY);
    Vector2f aMax = new Vector2f(aX + aWidth, aY + aHeight);

    Vector2f bMin = new Vector2f(bX, bY);
    Vector2f bMax = new Vector2f(bX + bWidth, bY + bHeight);

    float left = bMin.x - aMax.x;
    float right = bMax.x - aMin.x;
    float top = bMin.y - aMax.y;
    float bottom = bMax.y - aMin.y;

    if(left > 0) return 0;
    if(right < 0) return 0;
    if(top > 0) return 0;
    if(bottom < 0) return 0;

    int returnCode = 0;

    if (Math.abs(left) < right)
    {
        returnCode = 2;
    } else {
        returnCode = 4;
    }

    if (Math.abs(top) < bottom)
    {
        returnCode = 1;
    } else {
        returnCode = 3;
    }

    return returnCode;
}

当 A 与形状 B 的顶部、左侧或右侧碰撞时,返回数字 3,当与底部碰撞时,返回数字 1。我真的不知道是什么原因造成的。我的代码有什么问题?

4

2 回答 2

2

使用这些 if 块,您将始终得到1or3因为第二个 if 块将始终独立于您在第一个中设置的内容执行。

if (Math.abs(left) < right)
{
    returnCode = 2;
} else {
    returnCode = 4;
}

if (Math.abs(top) < bottom)
{
    returnCode = 1;
} else {
    returnCode = 3;
}
于 2012-12-22T00:15:56.767 回答
1

问题是您正在检查一侧,但是当您通过示例检查左侧并且底部也发生碰撞时,您忽略了那一侧。我在这里测试了代码:http ://wonderfl.net/c/i90L

我所做的是首先获取侧面 X 和 Y 的距离。然后检查哪个距离是最大的,乘以矩形本身的大小,因为那一边总是正方形上的好边。

    Vector2f returnCode = new Vector2f(0, 0);

    returnCode.x = (Math.abs(left) - right) * aWidth;
    returnCode.y = (Math.abs(top) - bottom) * aHeight;

    int temp = 0;

    if(returnCode.x > 0){
        //Hits left
        temp = 2;
    }else{
        //Hits right
        temp = 4;
    }

    if(returnCode.y > 0){
        //Hits top
        if(returnCode.y > Math.abs(returnCode.x)){
            temp = 1;
        }
    }else{
        //Hits bottom
        if(returnCode.y < -Math.abs(returnCode.x)){
            temp = 3;
        }
    }

    return temp;
于 2012-12-22T15:53:45.467 回答