xxxxxxxxxx
// Simulation of a single ball bouncing around a rectangle
// global variables
let width = 600
let height = 400
radius = 16;
// start in the center
x=width / 2;
y=height / 2;
// set the initial speed
let speedX = 3;
let speedY = 3;
function setup() {
createCanvas(width, height);
fill('black'); // set black color for the ball
strokeWeight(0); // hide border around the ball
}
function draw() {
background(220);
// Check for edges
if (x > width-radius || x < radius) {
speedX *= -1; // reverse direction
}
if (y > height-radius || y < radius) {
speedY *= -1;
}
// Calculate the new position
x += speedX;
y += speedY;
// draw the ball at its new location
circle(x, y, radius * 2);
}