2

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

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

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));

}
4

1 回答 1

1

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

障碍2:

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

12025

障碍3:

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

12200

12025 < 12200 -> 屏障 2 更近

编辑:在您编辑的答案中,您忘记平方 objectRadius 和 barrierRadius。例如

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

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

于 2013-03-27T02:36:34.427 回答