我怎样才能减慢随机生成率?

How can I slow down the random generation rate?

我刚开始学习 P5 和 JavaScript,我已经成功创建了一个 canvas,上面生成了随机模式。但是,似乎所有内容都是以相同的帧速率生成的,这使得某些 objects/shapes 看起来太快了。我尝试将帧速率更改为较慢的值,但它减慢了整个过程。

我怎样才能只减慢随机生成的圆圈的速度,同时保持其他一切都保持相同的速度?谢谢!

// Variables for randomCircles function with squares occuring at random times
var spot = { 
  x: 1000,
  y: 500
}

var col= {
  r: 255,
  g: 0, 
  b: 0
}

var angle = 0;

var x = 10;

function setup() { 
  frameRate(12);
  background(45, 46, 45);
  createCanvas(600, 600);
}

function draw() {
  // Changing background color of canvas to a dark gray
  background(45, 46, 45);
  //background(255, 255, 255);
  targets();
  deadlyLaser();
  randomCircles();
  harmlessLasers();
  player();

// Four targets or "bars of gold" in the background
function targets() {
  push();
  var x = 0;
    while (x < width) {  
      fill(235, 200, 37); 
      stroke(235, 200, 37); 
      rect(x + 40, 300, 25, 25);
      x = x + 100
      pop();
    } 
}

// Rotating laser
function deadlyLaser(){
  push();
  translate(300, 300);
  rotate(-angle/15);
  strokeWeight(2);
  stroke(235, 40, 26);
  // Last parameter is opacity
  fill(235, 72, 59, 127);
  rect(0, 0, 400, 400);
  x = x + 1;
  angle = angle + 2;
  pop();
}

// Random circles appearing at random times with random color
function randomCircles(){
  push();
  noStroke();
  // Randomizing positions of circles within canvas
  spot.x = random(0, width);
  spot.y= random(0, height);
  // Giving circles opacity in lass parameter; full is 255
  fill(41, 227, 235, 200);
  ellipse(spot.x, spot.y, 50, 50);
  pop();
}

// Lasers going back and fourth, happening at spontaneous times, with a hint of random color   
function harmlessLasers(){  
  push();
  stroke(random(131, 152), random(219, 255), random(167, 195));
    for (var x = 0; x < 20; x++) {
      var y = randomGaussian(800, 1400);
      line(300, 300, x, y);
      pop();
    }
}

// Player line that appears when mouse is on canvas
function player(){
  push();
  stroke(0, 224, 64);
  strokeWeight(6);
  line(mouseX, mouseY, pmouseX, pmouseY);
  print(pmouseX + " - " + mouseX);
  pop();
 }
}

可以使用frameCount变量或millis()函数来做时序相关的逻辑。这是一个小例子:

function setup() {
  createCanvas(400, 400);
}

function draw() {

    // add a circle once per second
    if(frameCount % 60 == 0){
        ellipse(random(width), random(height), 20, 20);
    }
}

相关帖子:

更多信息请参考the P5.js reference

一个简单的解决方案是将时间与之前的时间进行比较,看看是否已经过了足够的时间。

let timeLastUpdated = Date.now() // will hold the current date/time in milliseconds

您现在唯一需要的是再次随机化之前经过的时间常数,然后进行比较

const TIME_BETWEEN_RANDOMIZATIONS = 1000; // milliseconds between new randoms

然后在生成新随机数之前,将经过的时间与常量进行比较,看看我们是否准备好生成新随机数:

if (Date.now() - timeLastUpdated > TIME_BETWEEN_RANDOMIZATIONS) {
   // generate new random numbers
   spot.x = random(0, width);
   spot.y = random(0, height);

   // update the time
   timeLastUpdated = Date.now();
}