我无法理解为什么这不起作用。
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语句并且无条件地将推送器推送到refP时,它不会给我循环。
感谢。请告诉我是否应该清理此代码,或者尝试用更少的代码来隔离问题。
答案 0 :(得分:2)
您确定random
和dist
功能正常吗?
用{/ p>替换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);
为我工作。