Java 碰撞检测未按预期运行

标签 java collision-detection collision lwjgl

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

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。我真的不知道是什么原因造成的。我的代码有什么问题?

最佳答案

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

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

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

关于Java 碰撞检测未按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13998791/

相关文章:

python - Pygame - Sprite 与 Sprite 组的碰撞

swift - spritekit 快速碰撞检测不起作用

java - 旋转像素完美碰撞检测

python - 谁能告诉我如何使打印屏幕变蓝?

java - 我对 Java 中的通配符有一些错误的概念

java - 无需使用 IDE 即可格式化存储库中的 java 代码的工具

java - 只允许在 JTextField 中输入数字和符号 (-)

java - 如何访问 Hibernate Query 返回的值?

java - 为什么 LinkedList 没有遍历所有实体?

hash - 一个 32 位散列与两个 16 位散列之间是否存在冲突率差异?