Υποενότητα 9.2: Προηγμένες συναρτήσεις και μετασχηματισμοί στο p5
Συνάρτηση random
Η random() iείναι μια συνάρτηση p5.js η οποία επιστρέφει έναν τυχαίο αριθμό από τα καθορισμένα ορίσματα.
Μπορούμε να το χρησιμοποιήσουμε για να επιτύχουμε πολλά πράγματα, όπως: τοποθέτηση στοιχείων σε τυχαία θέση, τυχαία μετακίνηση στοιχείων, δημιουργία σχημάτων τυχαίου μεγέθους κλπ.
Μπορεί να πάρει 0,1 ή 2 ορίσματα.
- Αν καθορίζονται 0 ορίσματα, επιστρέφει έναν αριθμό μεταξύ [0,1).
- Αν έχει οριστεί 1 όρισμα, επιστρέφει αριθμό μεταξύ [0, αριθμός).
- Εάν έχουν οριστεί 2 επιχειρήματα, επιστρέφει έναν αριθμό μεταξύ [αριθ. 1, αριθμός 2].
Παράδειγμα
Ακολουθεί ένα παράδειγμα κώδικα που δημιουργεί ελλείψεις σε τυχαίες θέσεις και με τυχαίο μέγεθος:
//create variable for ellipse size
let size;
function setup() {
createCanvas(800, 600);
background(75);
}
function draw() {
// the size of the ellipses will be between (20,200]
let size = random(20, 200);
// all of x ,y and size of the ellipse will be random
// the x position will be between (size,(width-size)] so that the ellipse will always be within canvas
// the y position of the ellipse will also be always inside the canvas
ellipse(random(size, (width-size)), random(size, (height-size)), size);
}
You can see the result of the above code here
Exercise
- Open your Visual Studio editor and the
p5yourNamefolder. - Open the file
ex812.jsin your editor and save it asex925.js - Open the file
ex812.htmlin your editor and save it asex925.html - In the
ex925.htmlfile, update the link toex925.jsfrom exersice812.js - Go to the
index.htmlfile and create, underModule 9, alinkto theex925.htmlfile with the title "random".
Modify the ex925.jsfile and use as a base the above example to make the ellipses taking random colors. You can see here an example.
//create variable for ellipse size
let size;
function setup() {
createCanvas(800, 600);
}
function draw() {
background(67,34,89);
// the size of the ellipses will be between (20,200]
let size = random(20, 200);
// create random fill for the ellipses
fill(random(1, 256),random(1, 256),random(1, 256));
// all of x ,y and size of the ellipse will be random
// the x position will be between (size,(width-size)] so that the ellipse will always be within canvas
// the y position of the ellipse will also be always inside the canvas
ellipse(random(size, (width-size)), random(size, (height-size)), size);
}
Κάντε μια Git commit με το μήνυμα "random".
- Δείτε περισσότερα για την random() function