如何降低随机产生率?

时间:2018-06-29 18:49:28

标签: javascript p5.js

我刚刚开始学习P5和JavaScript,我设法创建了一个画布,上面生成了随机模式。但是,似乎所有东西都以相同的帧速率生成,这使得某些对象/形状显得过快。我尝试将帧速率更改为较慢的速度,但这会减慢整个速度。

我如何才能放慢随机产生的圆的速度,同时保持其他所有速度相同?谢谢!

// 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();
 }
}

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

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

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();
}