0

我一生都无法弄清楚为什么这不起作用。

var refP = [];
var distance = function (p1, p2) {
    return dist(p1.x, p1.y, p2.x, p2.y);
}
while (refP.length < 24) {
    var pusher = {
        x: -1,
        y: -1,
        closestRefP: 9999999
    };
    pusher.x = (random(0, 400));
    pusher.y = (random(0, 400));
    for (var d = 0; d < refP.length; d++) {
        if (distance(pusher, refP[d]) < pusher.closestRefP) {
            pusher.closestRefP = distance(pusher, refP[d]);
        }
    }
    if (pusher.closestRefP > 2) {
        refP[refP.length] = pusher;
    }
}

当我删除最后一个 if 语句并无条件地将 pusher 推到 refP 上时,它不会给我循环。

谢谢。如果我应该清理这段代码,或者尝试用更少的代码隔离问题,请告诉我。

4

1 回答 1

2

您确定您的randomdist功能正常吗?

将您的distance功能替换为:

var distance = function (point1, point2) {
  var xs = 0;
  var ys = 0;

  xs = point2.x - point1.x;
  xs = xs * xs;

  ys = point2.y - point1.y;
  ys = ys * ys;

  return Math.sqrt( xs + ys );
}

和你的random(0, 400)电话:

pusher.x = Math.floor(Math.random() * 400);
pusher.y = Math.floor(Math.random() * 400);

为我工作。

于 2013-05-25T11:42:47.103 回答