Your first real animation
Time to combine three things you've already learned into one moving sketch: variables to remember where the ball is and how fast it travels, the `draw()` loop to redraw it ~60 times a second, and conditionals to make it turn around at the walls.
The big idea behind almost every animation is this: keep a value in a variable, change it a little every frame, and draw using that value. A ball that moves right is just x = x + speed repeated over and over.
Remembering position
We declare the ball's position outside draw() so the value survives between frames. If we declared it inside, it would reset to the start every single frame and the ball would never go anywhere.
let x = 200;
let speed = 4;
function draw() {
background(220);
x = x + speed; // move a little each frame
ellipse(x, 200, 40, 40);
}Bouncing with a conditional
Left alone, the ball sails off the right edge forever. To bounce, we check its position with an if: when it reaches an edge, we flip the direction by negating the speed. speed = -speed turns 4 into -4 (now moving left) and -4 back into 4.
Why negate the speed?
Flipping the sign is the whole trick. A positive speed moves right (or down); a negative one moves the opposite way. speed = -speed reverses the direction without you tracking which way it was going.
Now you'll do the full version: a ball that bounces off all four walls. That means tracking both an x and a y, giving each its own speed, and checking each against its edges.