Last night a student and I set out to clone a sketch I found on Twitter:

The first task, as always, is to analyze the sketch to break it down into its repeated components. In this case, the repeated component is a circle that oscillates back and forth along a line. I challenged my student to create that in Processing. He needed a refresher on the sine function. You don't have to sit through a year-long trig class to know sine can be used to make things oscillate between a minimum and maximum value. It includes the whole range of values in between, too. The general form of the equation for a sine wave is

f(t) = a*sin(b*t - c)

where t is the time variable, a is the height of the wave, b is the frequency of the oscillation and c is the phase shift. The equation for making the x-value oscillate between -300 and 300 (for a 600-pixel screen) is

x = 300*sin(0.05*frameCount)

because frameCount is a built-in value in Processing that returns the number of frames that the program has looped through already. With that we could create a line and oscillate one ball back and forth across it:

Using a loop and the rotate function, we could create that ball, rotate the screen a little, and loop over again and again. However, All the balls would be the same distance down the line, and it wouldn't look as cool.

We had to mess with the phase shift to get it to look right. Here's the line of code:

shift = i * PI / num

where num is the total number of balls we want (8) and i is the variable (between 0 and 7) for which ball we're drawing. With that we'd succeeded at cloning the Twitter sketch. But we had one trick left. Since we were smart and used variables for the number of balls, we could vary that manually by mapping the location of the mouse. That meant we could move our mouse and dynamically change the number of balls we drew! Very cool!