p5.js introductory tutorial ball animation sample code

亚连
Release: 2018-05-30 10:01:13
Original
1922 people have browsed it

This article mainly introduces the ball animation sample code of the p5.js introductory tutorial. Now I share it with you and give it as a reference.

1. Moving 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. Since the draw() function will continue to run (frequency is FPS, default 60 frames/second), So the ball moves.

The code is as follows:

var x=0; function setup() { createCanvas(400, 400); } function draw() { background(220); //width和height是关键词,分别是Canvas的宽和高 x+=2; ellipse(x,height/2,20,20); }
Copy after login

##2. The bouncing ball

After a period of time, the ball will move out of the screen. In order to prevent the ball from running 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/2,20,20); //width和height是关键词,分别是Canvas的宽和高 x+=speed; if(x>width||x<0){ speed*=-1; }
Copy after login

Further, we can use two variables to control the speed in the x and y directions to realize the movement of the ball on the canvas Ejection function.

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和height是关键词,分别是Canvas的宽和高 x+=Vx; y+=Vy; if(x>width||x<0){ Vx*=-1; } if(y>height||y<0){ Vy*=-1; } }
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Nodejs simple method of reading and writing excel content

node.js blog project development notes

Detailed explanation of the difference between "==" and "===" in javaScript

The above is the detailed content of p5.js introductory tutorial ball animation sample code. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!