In this learning activity, students will understand the concept of functions in a different way because unlike other functions we have been using (i.g. ellipse and rect) random will return a value. Rect() "returns" an image by generating it onto the canvas. The random() function will be one of many functions that will be used in future units in order to make sketches more complex and interactive.
Students will be able to:
- Use
random()
to generate different positioning, sizing and grayscale fill
- Assign
random()
to a function
- Use
random()
in the correct scope
Place elements at random positions
We can also place our ellipse at a random position each time our program runs. To do this, we use p5's random
function. This function is different from other functions we have been using (like ellipse
and rect
) in that it returns a value. Each time they are called:
random(50, 100)
returns a number between 50 and 100
random(1, 5)
returns a number between 1 and 5
When the first parameter is omitted, random assumes it is 0:
random(100)
returns a number between 0 and 100
random(5)
returns a number between 0 and 5
In the p5 editor, try running the following piece of code several times:
function setup(){
ellipse(random(100), 60, 60, 60);
}
Now try these, and play with their values:
ellipse(random(100),random(100), 60, 60);
ellipse(random(300, 400), 60, 60, 60);
ellipse(random(20, 60), random(60, 120), 60, 60);
What happens if we replace the last two parameters with calls to random
?