【问题标题】:Detect Collision with arrays in Java [closed]在Java中检测与数组的冲突[关闭]
【发布时间】:2017-06-14 07:18:57
【问题描述】:

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

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

    }
}

如果发生冲突,该方法必须返回 true。

【问题讨论】:

  • 欢迎来到 Stack Overflow!看起来你正在寻求家庭作业帮助。虽然我们对此本身没有任何问题,但请注意这些dos and don'ts,并相应地编辑您的问题。
  • 这里的objects 是什么意思?

标签: java arrays collision


【解决方案1】:

您可以使用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);
    }
}

【讨论】:

  • 你为什么用static这个词?平行宇宙中可能存在不同的物理学;)
猜你喜欢
  • 1970-01-01
  • 2021-01-29
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多