xxxxxxxxxx
35
// Keep track of the horizontal position of the ball
let x;
// Keep track of the dir of movement
let xspeed = 1;
function setup() {
createCanvas(400, 400);
// Start in the middle
x = width/2;
}
function draw() {
background(220);
// Flip the direction of movement when the ball passes the left or right boundary of the canvas
if(x < 0 || x > width) {
xspeed *= -1;
}
// Move the ball
x += xspeed;
// Fill the color
// Map the position of the ball to the fill color
let c = map(x, 0, 400, 0, 255);
// This is the same math as:
// c = x * width/255;
// Fill with the calculated color
fill(c);
// Draw the ball
ellipse(x, height/2, 50, 50);
}