Using fxrand() for p5 project?

1.2k Views Asked by At

I used the p5 editor to build an nft, and I'm working on getting it working in the fxhash sandbox. Using p5's random() function worked great when I uploaded my project to the sandbox, but quickly realized I needed to implement the fxrand() function to ensure that each individual iteration is the same when refreshing with the same hash.

Simply replacing all instances of the p5 random() function with fxrand() did not work, and I'm assuming because fxrand() simply generates a random number, whereas p5's random() function can be used in other ways (ie; random(-50, 50)).

How do I need to incorporate the fxrand() function into my project in a way that still works the same way as p5's random() function?

2

There are 2 best solutions below

0
On

You may have already figured this out, and there's probably far better solutions (I'm very new to this), but here is what I figured out.

If I need a number from 0 to 9 then I can use this:

let randChoose1 = Math.floor(fxrand() * 10;

Anywhere I need to call that number I can simply use randChoose1 in place. For example, if I have an array named "bg" with 10 entries in the array, and I want to choose something from the array I can do this:

let randoBg = bg[randChoose1];

Maybe that's an image that I want to center on the canvas, I can call it with:

image(randoBg, width / 2, height / 2);

If I have 23 items in the array then I just need to declare randChoose1 with:

let randChoose1 = Math.floor(fxrand() * 23);

If you want to be able to have negative numbers be chosen, such as your example of a range from -50 to 50, it's just a matter of multiplying by rough total range you want and then subtracting half that.

let randChoose1 = Math.floor(fxrand() * 101 - 50;

In this case, randChoose1 will give you that range of results from -50 to 50. You have to multiply by 101 in order to make it possible for Math.floor to deliver 100 since it always rounds down.

If you found a better solution I'd love to hear it! This is something I'm struggling with as well, and my total experience with p5.js is less than a week at this point.

0
On

If you use randomSeed(int(fxrand()*987654321)) at the beginning of the setup function every time you call to the random function it will depend on fxrand