How to make a variable random in p5.js

Hi, I’m playing around with a color wheel by kgrnbrg.

I want to randomize the segmentCount so the color wheel can change shape and thereby adjusting the number of colors available.

I can’t use random in the top and if I place the variable locally and use random() it draws the entire color wheel again and again.

I can’t use noLoop() as I need it to be running for some other purpose later on.

So how can I randomize the segmentCount with the above limitations?


var segmentCount = 24;
var radius;
function setup() {
radius = 300;

function draw() {
colorMode(HSB, 360,width,height);
//floor is a fancy way of saying,
//round downward so that our resulting value is the
//nearest whole number
var angleStep = floor(360/segmentCount);
//there are different drawing modes with beginShape()
//to learn more, go to:
for(var angle =0; angle <= 360; angle += angleStep){
var vx = width/2 + cos(radians(angle))* radius;
var vy = height/2 + sin(radians(angle))* radius;
vertex(vx, vy);
fill(angle, mouseX, mouseY);

Hello @x06

Since setup() runs just once (it is only draw() that loops—you can place random() function in setup. In this case, make sure to round up using ceil(). Then assign that random variable to the segmentCount variable.
Alternately you can use randomSeed() and place that in draw.
See reference for full explanations on randomSeed() and ceil().

Good luck!

BTW, in future posts please format your code. It is difficult to read unformatted… :slight_smile:

1 Like

Thank you so much for helping! Gonna try it out :slight_smile:

And thanks for the heads up on formatting - newbie here - so really appreciate do’s and don’ts

Hmm, can’t make it work. When I declare the SegmentCount in Setup it is no longer a global var and thus, it can’t find it in draw… I kind of know that you assumed that I could get around this problem myself… but I can’t :slight_smile: Sorry

Prior to setup() do this:

let SegmentCount;

That makes the name SegmentCount global. Thereafter, you can assign the variable a value wherever else it is necessary. Inside setup() or draw(), do not begin the assignment statement with let, or you will be declaring a local variable with the same name.

1 Like

Heeeeeyyy that worked! My hero :slight_smile: Thanks for helping out a newbie - much appreciated

1 Like