在 Java 中检测与阵列的碰撞

Detect Collision with arrays in Java

好的,所以我想建立一个方法来检测两个物体是否发生碰撞。他们的命中框存储在数组中。像这样 [topLeftX, topLeftY, bottomRightX, bottomRightY] 对于两个对象中的每一个。我无法找出正确的 if 语句来使用这两个数组来检测这一点。

public class Physics {
    public static boolean isColliding(int ob1Hitbox[], int ob2Hitbox[]) {

    }
}

如果发生碰撞,该方法必须 returns 为真。

您可以使用 Rectangle#intersects 来为您完成计算:

import java.awt.Rectangle;

public class Physics {
    public static boolean isColliding(int[] ob1Hitbox, int[] ob2Hitbox) {
        return toRectangle(ob1Hitbox).intersects(toRectangle(ob2Hitbox));
    }

    private static Rectangle toRectangle(int[] hitbox) {
        int x = hitbox[0];
        int y = hitbox[1];
        int width = hitbox[2] - x;
        int height = y - hitbox[3];
        return new Rectangle(x, y, width, height);
    }
}