检测数组中最接近的元素

时间:2013-03-27 02:08:52

标签: java arrays for-loop indexing distance

我在向玩家检测块数组中最近的元素时遇到问题(使用圆圈)。

到目前为止我所拥有的是:

public static int closestBarrier(GameObject object, GameObject[] barriers) {
    int closest = -1;
    float minDistSq = Float.MAX_VALUE;// ridiculously large value to start
    for (int i = 0; i < barriers.length; i++) {

        float barrierRadius = barriers[i].getWidth() / 2;
        float objectRadius = object.getWidth() / 2;

        GameObject curr = barriers[i];// current
        float dx = (object.getX()) - ((curr.getX()));
        float dy = (object.getY()) - ((curr.getY()));
        float distSq = (((dx * dx + dy * dy) - objectRadius) - barrierRadius)  ;// use the squared distance
        if (distSq < minDistSq) {// find the smallest and remember the id
            minDistSq = distSq;
            closest = i;
        }
    }

    return closest;
}

它通过了大多数测试但是在最后一个测试中,最接近的测试的返回索引是2而不是预期的3.这是测试(它是'最接近第四'的失败:

    public final void testClosestBarrier() {
    // Closest to first
    GameObject player = new GameObject(0,1);
    player.setWidth(2);
    GameObject[] barriers = new GameObject[4];
    barriers[0] = new GameObject(8,9);
    barriers[0].setWidth(3);
    barriers[1] = new GameObject(10,15);
    barriers[1].setWidth(2);
    barriers[2] = new GameObject(15,20);
    barriers[2].setWidth(5);
    barriers[3] = new GameObject(100,210);
    barriers[3].setWidth(10);
    assertEquals("Player closest to first barrier",0,
            Submission.closestBarrier(player,barriers));

    // Closest to second
    player.setX(12);
    player.setY(12);
    assertEquals("Player closest to second barrier",1,
            Submission.closestBarrier(player,barriers));

    // Closest to third
    player.setX(12);
    player.setY(20);
    assertEquals("Player closest to third barrier",2,
            Submission.closestBarrier(player,barriers));

    // Closest to fourth
    player.setX(90);
    player.setY(100);
    assertEquals("Player closest to fourth barrier",3,
            Submission.closestBarrier(player,barriers));

}

1 个答案:

答案 0 :(得分:1)

您的代码是正确的,您所编写的测试是错误的 - 屏障2比屏障3更接近90,100。

障碍2:

(90-15)^ 2 +(100-20)^ 2

12025

障碍3:

(100-90)^ 2 +(210-100)^ 2

12200

12025&lt; 12200 - &gt;屏障2更接近

编辑:在您编辑的答案中,您忘记了对象objectRadius和barrierRadius。 e.g。

float distSq = (((dx * dx + dy * dy) - objectRadius) - barrierRadius)

在这一行中,你有dx ^ 2,dy ^ 2但只有非平方的objectRadius和barrierRadius。