【问题标题】:How do I set random values in processing that are in certain intervals如何在特定间隔的处理中设置随机值
【发布时间】:2018-11-22 04:41:21
【问题描述】:

例如,我试图做到这一点,当其中一个圆圈离开屏幕边缘时,它会将其 X 坐标重置为 -100,0 或 840,940 之间的任何位置。这是因为我希望它从另一个随机位置移回屏幕。

有没有办法在这样的处理中使用随机函数?

我能想到解决这个问题的唯一方法就是这样做:

//in my real program this would be taking place in a for loop parsing through an array 
int = random(1,2);
if(x = 1){
   posX[i] = random(-100,0);
}
else{
   posX[i] = random(840,940);
}

但这会占用额外的空间。我假设有一些方法可以在某个时间间隔内创建随机值。

【问题讨论】:

    标签: processing


    【解决方案1】:

    你所拥有的基本上就是我会采取的方法。您的代码存在一些问题:您使用的是= 而不是==,并且您正在比较1 而不是范围。你可能想要这样的东西:

    float x = random(1);
    if(x < .5){
      myValue = random(-100, 0);
    }
    else{
      myValue = random(840, 940);
    }
    

    编程的一个很酷的地方是您可以创建自己的函数,如下所示:

    float getValueFromRanges(float startOne, float endOne, float startTwo, float endTwo){
    
      if(random(1) < .5){
        return random(startOne, endOne);
      }
      else{
        return random(startTwo, endTwo);
      }
    }
    

    然后,只要您想从这些范围中获取随机值,您就可以调用此函数:

    float myValue = getValueFromRanges(-100, 0, 840, 940);
    

    或者您可以使用三元运算符在一行代码中执行此操作:

    float myValue = random(1) < .5 ? random(-100, 0) : random(840, 940);
    

    最后一种方法可读性不强,所以我可能会创建一个函数。

    【讨论】:

      猜你喜欢
      • 2017-08-28
      • 2011-05-23
      • 2016-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      相关资源
      最近更新 更多