P5.js getting started tutorial-small ball animation sample code, p5.js sample code

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.