Υποενότητα 8.2: p5.js Τα Βασικά
Υποενότητα 8.2: p5.js Τα Βασικά
- Συναρτήσεις setup() and draw()
- Συνάρτηση createCanvas()
- Βασικά σχήματα - Primitives Shapes
Κίνηση
Το P5.js μας δίνει τη δυνατότητα να δημιουργούμε εύκολα κίνηση / animation αντικειμένων.
Αν και αυτή η έννοια είναι νέα, η βάση είναι η καλή κατανόηση των συντεταγμένων του καμβά.
Τώρα που έχετε δημιουργήσει κάποια σχήματα και έχετε εξοικειωθεί με τις συντεταγμένες του καμβά, είναι καιρός να χρησιμοποιήσετε τις νέες γνώσεις σας μαζί με τη JavaScript για να δημιουργήσετε ένα απλό κινούμενο σχέδιο. Πώς θα δημιουργούσατε μια ελλειπτική κίνηση που θα κινηθεί οριζόντια από το αριστερό προς το δεξί άκρο του καμβά σας και αντίστροφα;
// create a variable to control the direction of the ellipse
let control = false;
// make ellipse starting from the left end of the canvas
let i=30;
function setup() {
// create canvas
createCanvas(800,500);
// set background color
background('#31bc33');
}
function draw () {
// when ellipse is in the left edge, control would be/become false
if (i==30) {
control = false;
}
// if ellipse is inside the canvas width (we substract 30 which is the radius
// of our ellipse) and control is false
if (i<(width-30) && control==false){
i++
// increase its x position (ellipse moves in the right direction)
ellipse(i,height/2,60);
}
else {
// else control will change to true
control = true;
// decrease its x position (ellipse moves in the left direction)
i--;
ellipse(i,height/2,60);
}
}
Δείτε here το παράδειγμα.
Μπορεί να έχετε παρατηρήσει ότι η έλλειψη σας αφήνει ίχνη καθώς κινείται μέσα από τον καμβά. Γιατί νομίζετε ότι αυτό συμβαίνει; Τι θα κάνατε αν θέλετε να το αλλάξετε;
Exercise
- Open your Visual Studio editor and the
p5yourNamefolder. - Open the file
ex812.jsin your editor and save it asex828.js - Open the file
ex812.htmlin your editor and save it asex828.html - In the
ex828.htmlfile, update the link toex828.jsfrom ex812.js - Go to the
index.htmlfile and create, underModule 8, alinkto theex828.htmlfile with the title "Motion".
Modify the ex828.jsfile in order to create a two-dimensional motion with collisions You can see here an example.
Do a Git commit with the message "Motion".