# Oscillations

An understanding of the concepts of oscillation, amplitude, and frequency/period is often required in the course of simulating real-world behaviors. However, there is a slightly easier way to rewrite the above example with the same result. Let’s take one more look at our oscillation formula:

var x = amplitude * sin(TWO_PI * frameCount / period);

And let’s rewrite it a slightly different way:

var x = amplitude * sin(some value that increments slowly);

If we care about precisely defining the period of oscillation in terms of frames of animation, we might need the formula the way we first wrote it, but we can just as easily rewrite our example using the concept of angular velocity (and acceleration) from the Angular Motion lesson. Assuming:

var angle = 0;
var aVelocity = 0.03;

...in draw(), we can simply say:

angle += aVelocity;
var x = amplitude * sin(angle);

...where angle is our “some value that increments slowly.”

Here's our modified program:

Just because we’re not referencing it directly doesn’t mean that we’ve eliminated the concept of period. After all, the greater the angular velocity, the faster the circle will oscillate (therefore lowering the period). In fact, the number of times it takes to add up the angular velocity to get to TWO_PI is the period or:

period = TWO_PI / angular velocity

Let’s expand this example a bit more and create an Oscillator object. And let’s assume we want the oscillation to happen along both the x-axis (as above) and the y-axis. To do this, we’ll need two angles, two angular velocities, and two amplitudes (one for each axis). Another perfect opportunity for PVector!

Read through the code in the program below:

This "Natural Simulations" course is a derivative of "The Nature of Code" by Daniel Shiffman, used under a Creative Commons Attribution-NonCommercial 3.0 Unported License.