xxxxxxxxxx
55
/*
Animation
*/
// position of the ball
let x = 200;
let y = 200;
let ySpeed = 5; // Vertical speed
let xSpeed = 5; // Horizontal speed
function setup() {
createCanvas(500, 400);
textAlign(CENTER, CENTER);
}
function draw() {
background(220);
// draw the ball
fill("pink");
ellipse(x, y, 50);
// draw text around the ball
fill(0);
text("BALL", x, y + 10);
text("BALL", x, y - 10);
// animate the ball
x += xSpeed;
y += ySpeed;
// Bounce off the right edge
if (x > width - 25) {
xSpeed *= -1; // Reverse direction
}
// Bounce off the left edge
if (x < 25) {
// 25 is half the width of the ball
xSpeed *= -1;
// Reverse direction
}
// Bounce off the bottom edge
if (y > height - 25) {
// 25 is half the height of the ball
ySpeed *= -1;
}
// Bounce off the top edge
if (y < 25) {
ySpeed *= -1; // Reverse direction
}
}