Variables, exspressions, and random Oh My!!
I’m starting to see how the building blocks of p5.js will enable the creation of systems and thusly enable more complex programs to be written.
Variables, expressions, and random()
Oh My!!
I’m starting to see how the building blocks of p5.js will enable the creation of systems and thusly enable more complex programs to be written. There are however, a few concepts that still are a bit fuzzy. One of those is random()
, I understand how this function works but I’m a bit lost as to why I can put it before the setup()
so that it can have an affect on the code after it. I was able to find a work around unfortunately this creates a very long program to something I believe should be able to be done with far fewer lines of code.
You can see in the code below the video lines 22-41 and lines 52-70 are devoted to assigning a random color to the four circles. This seems like a lot of code to produce these changes. This is where I’m sure this is a better more compact way to do this.
The video is a screen recording of the behavior produced by this code. The circles which have an origin at the four corners has a random()
assignment operation for location. The color of each circle is also is random()
unless the (mouseButtonPressed)
is used which changes each of the circles to red, green, blue, or black.
var circleObject1 = { x: 0, y: 0, d: 25 } var circleObject2 = { x: 599, y: 0, d: 25 } var circleObject3 = { x: 0, y: 599, d: 25 } var circleObject4 = { x: 599, y: 599, d: 25 } var col1 = { r: 50, g: 50, b: 50 } var col2 = { r: 10, g: 10, b: 10 } var col3 = { r: 100, g: 100, b: 100 } var col4 = { r: 225, g: 225, b: 225 } function setup() { createCanvas(600, 600); } function draw() { background(220); frameRate(10); col1.r = random(0, 255); col1.g = random(0, 255); col1.b = random(0, 255); col2.r = random(0, 255); col2.g = random(0, 255); col2.b = random(0, 255); col3.r = random(0, 255); col3.g = random(0, 255); col3.b = random(0, 255); col4.r = random(0, 255); col4.g = random(0, 255); col4.b = random(0, 255); col1.r = random(0, 255); col1.g = random(0, 255); col1.b = random(0, 255); circleObject1.x = random(0, 299) circleObject2.x = random(300, 599) circleObject3.x = random(0, 299) circleObject4.x = random(300, 599) noStroke() circle(circleObject1.x, circleObject1.y, circleObject1.d = circleObject1.d + 10); if (mouseIsPressed) { fill(0, 0, 255); } else { fill(col1.r, col1.g, col1.b); } circle(circleObject2.x, circleObject2.y, circleObject2.d = circleObject2.d + 10); if (mouseIsPressed) { fill(255, 0, 0); } else { fill(col2.r, col2.g, col2.b); } circle(circleObject3.x, circleObject3.y, circleObject3.d = circleObject3.d + 10); if (mouseIsPressed) { fill(0); } else { fill(col3.r, col3.g, col3.b); } circle(circleObject4.x, circleObject4.y, circleObject4.d = circleObject4.d + 10); if (mouseIsPressed) { fill(0, 255, 0); } else { fill(col4.r, col4.g, col4.b); } }
Text content