2017-02-17 70 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; 
}