2017-02-17 66 views
0

我是新來javascript編程,但我知道我的代碼是多麼混亂,所以我很抱歉。我試圖做的是創建2(現在,最終版本將有很多)「樹」,只是矩形現在放置在一個隨機的x值。但我不希望它們在彼此的40像素範圍內。我一直在試圖寫一些應該達到這個目標的東西,但我無法弄清楚爲什麼它不能工作,樹木依然在彼此之上產卵!這讓我瘋狂。順便說一下,我使用p5js和崇高文本2。我怎樣才能讓兩個隨機數保持一定的距離?

function bg(){ 
    var tree = Math.floor(Math.random() * (380 - 0) + 00); 
    var tree2 = Math.floor(Math.random() * (380 - 0) + 0); 
    redefine(tree,tree2); 
    this.x=0; 

    this.show = function(){ 
     noStroke(); 

     //tree 
     fill(102, 51, 0); 
     rect(this.x+tree , 450, 26, 110); 

     //tree2 
     fill(102, 51, 0); 
     rect(this.x+tree2, 410, 26, 150); 
    } 
} 

function redefine(first, second){ 
    if(second<=first-40 || second>=first+40){ 
     console.log("good"); 
    } else { 
     console.log("redefining") 
     second = Math.floor(Math.random() * (380 - 0) + 0); 
    } 
} 

//key 
// Math.random() * (max - min) + min  
+0

ü可以創建一個片段? –

+0

@DeepakSharma即時通訊不好意思是什麼片段? –

+0

像jsfiddle在stackoverflow。所以我們可以在這裏運行測試代碼 –

回答

0

一個問題是,你只給你的redefine函數一個機會滾動另一個隨機數。你可以把它改成一個循環,不斷嘗試,直到它們距離正確的距離。

0

在重新定義時,您嘗試更改「second」的值,但不會修改「tree2」,因爲它是本地範圍的基本變量。假設你的其他邏輯是合理的,這樣的事情可能工作:

function bg(){ 


var tree = Math.floor(Math.random() * (380 - 0) + 00); 
var tree2 = Math.floor(Math.random() * (380 - 0) + 0); 

while(isOverlapping(tree, tree2)) { 
    tree2 = Math.floor(Math.random() * (380 - 0) + 0); 
} 

this.x=0; 

this.show = function(){ 
noStroke(); 

//tree 
fill(102, 51, 0); 
rect(this.x+tree , 450, 26, 110); 

//tree2 
fill(102, 51, 0); 
rect(this.x+tree2, 410, 26, 150); 
    } 
} 

function isOverlapping(first, second){ 
    if(second<=first-40 || second>=first+40){ 
     console.log("good"); 
     return false; 
    } else { 
     console.log("redefining") 
     return true; 
    } 
} 
+0

這似乎使它完美的工作謝謝! –

0

我會建議使用「定義」的方式,而不是「重新定義」:

function bg() { 

    var tries = define(tree, tree2); 
    var tree = tries[0]; 
    var tree2 = tries[1]; 


    this.x = 0; 

    this.show = function() { 
    noStroke(); 

    //tree 
    fill(102, 51, 0); 
    rect(this.x + tree, 450, 26, 110); 

    //tree2 
    fill(102, 51, 0); 
    rect(this.x + tree2, 410, 26, 150); 
    } 

} 

function define() { 

    var tries  = []; 
     tries[0] = 0; 
     tries[1] = 0; 
    var i   = 0; 

    while(tries[1] - tries[0] <= 40 && tries[0] - tries[1] <= 40){ 

     tries[0] = Math.floor(Math.random() * (380 - 0) + 0); 
     tries[1] = Math.floor(Math.random() * (380 - 0) + 0);   
     i++; 
     console.info('iter:',i,' inside tree:',tries[0],' tree2:',tries[1]); 

    } 

    return tries; 
}