How do I create a random number that remains constant and doesn’t change in Javascript?

Tags: ,



I’m trying to have a few circles drawn on the screen that do not move after initialization. Right now it is constantly drawing them to the screen instead of keeping them there. Here’s the code:

for (let i = 0; i < 1; i++) {
    //location
    const r = random(100, 900);
    const r2 = random(900, 100);
    //size
    const rS = random(50, 250);
    const rS2 = random(250, 50);
    //draw the ellipse with parameters
    ellipse(r, r2, rS, rS2);
  }

(This is with the p5.js library)

Answer

It sounds like your code is in the draw() function, which is called multiple times a second. Since you call random() every single time, it creates new parameters every single time. Instead, you should assign parameters to a variable somewhere else (like in the setup function) and then use those in the draw function. Something like:

var ellipses = [];

function setup() {
  createCanvas(640, 480);
  for (let i = 0; i < 1; i++) {
    ellipses.push({
      r: random(100, 300),
      r2: random(300, 100),
      rS: random(50, 250),
      rS2: random(250, 50)
    });
  }  
}

function draw() {
  clear();
  //location
  //draw the ellipse with parameters
  ellipses.forEach(function (e) {
    ellipse(e.r, e.r2, e.rS, e.rS2);
  })
}
<script src="https://unpkg.com/p5@1.1.9/lib/p5.min.js"></script>


Source: stackoverflow