我試圖在畫布上創建不同半徑的三個點,它們不會相互接觸或重疊。我正在爲圈子使用Jquery和Raphael。但是,當我運行該程序時,它們有時會重疊/觸摸,但我無法在代碼中找到邏輯錯誤。我的代碼中的錯誤在哪裏?
$(document).ready(function() {
var canvasx = 1450;
var canvasy = 743;
var paper = Raphael(0, 0, canvasx, canvasy);
var circles = new Array;
var colorarray = new Array("black", "red", "blue");
var circleoffsetx = canvasx/4;
var circleoffsety = canvasy/4;
var iterations = 3;
var circleoverlap = false;
for (var i = 0; i < iterations; i++) {
var circlecolor = colorarray[Math.floor(Math.random() * colorarray.length)];
var circlex = Math.floor((Math.random() * canvasx/2) + circleoffsetx);
var circley = Math.floor((Math.random() * canvasy/2) + circleoffsety);
var circleradius = Math.floor((Math.random() * 75) + 25);
if (circles.length > 0) {
for (var j = 0; j < circles.length; j++) {
var allcirclex = circles[j[0]];
var allcircley = circles[j[1]];
var allcircleradius = circles[j[2]];
var radiussum = circleradius + allcircleradius;
if (Math.abs(circlex - allcirclex) <= radiussum || Math.abs(circley - allcircley) <= radiussum) {
iterations++;
circleoverlap = true;
console.log("OVERLAP");
break;
}
}
if (circleoverlap === false) {
circles.push(paper.circle(circlex, circley, circleradius).attr({"stroke": circlecolor, "stroke-width": 3}));
circles[i] = [circlex, circley, circleradius];
console.log("NO OVERLAP");
}
}
if (circles.length < 1) {
circles.push(paper.circle(circlex, circley, circleradius).attr({"stroke": circlecolor, "stroke-width": 3}));
circles[i] = [circlex, circley, circleradius];
}
console.log(circles[0]);
}
});
所以我創建一個圓,它保存的X,Y,在二維陣列(圓)半徑,然後想看看新的圈子會觸及/重疊現有的通過,如果距離看到在圓x,y之間小於或等於半徑之和。但再一次,它似乎並不奏效。我也是console.logging,如果它們重疊或不重疊(OVERLAP vs NO OVERLAP)並且它總是記錄NO OVERLAP。
男人,你的解決方案更有意義。我怎麼能學會這樣想?它 – AustriaNotAustralia
別擔心,我花了很長時間才能到達那裏:D所有你需要的是練習。 –