P5.js getting started tutorial-small ball animation sample code, p5.js sample code
I. Sports ball
In this section, we will use p5.js to make a small ball that moves on the screen.
The idea is to use variables to record the position of the ball and then change it in the draw () function, because the draw () function will continue to run (the frequency is FPS, the default value is 60 frames per second.
The Code is as follows:
Var x = 0; function setup () {createCanvas (400,400);} function draw () {background (220); // width and height are keywords, the width and height of the Canvas x + = 2; ellipse (x, height/, 20 );}
2. Rebound ball
After a period of time, the ball will be removed from the screen. To prevent the ball from going out of the screen, we add a variable to control the speed and reverse the speed when the ball leaves the screen.
The Code is as follows:
Var x = 0; var speed = 2; function setup () {createCanvas (400,400);} function draw () {background (220); ellipse (x, height, 20); // width and height are keywords, respectively, the width and height of the Canvas x + = speed; if (x> width | x <0) {speed * =-1 ;}
Further, we can use two variables to control the speed in the x and y directions, so that the ball can be shot on the canvas.
The Code is as follows:
Var x = 200; var y = 200; var Vx = 2; var Vy = 3; function setup () {createCanvas (400,400);} function draw () {background (220); ellipse (x, y, 20, 20); // width and height are keywords, which are the width and height of the Canvas x + = Vx; y + = Vy; if (x> width | x <0) {Vx * =-1;} if (y> height | y <0) {Vy * =-1 ;}}
Final effect: https://alpha.editor.p5js.org/full/Bya02GDBb
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.