Physical Simulations

More Complex Sine Waves

Here's an example of just how far we can push this stuff. If we combine the formula for a three-dimensional sine wave with our code for automatically distributing layers in a grid we can set up a pretty cool undulating grid. Please note that even though it appears that the layers are undulating in the y direction in the demo movie they are actually laid out in an x/y grid and are moving back and forth in the z direction. I moved the camera to give a better perspective view of the action. Here's the code for position:

undulating grid

``````
numCol = 8; //number of columns
gap = 20; // distance between cells (pixels)
amp = 40; //amplitude in pixels
wave = 100; //wavelength in pixels
freq = 0.5; //cycles per second

origin = [gap/2,gap/2,0]; //upper left hand corner of grid
x = ((index-1)%numCol)*gap;
y = Math.floor((index-1)/numCol)*gap;
z = 25*Math.cos((x + y)/wave + freq*Math.PI*2*time);

origin + [x,y,z]
``````

Almost all of this code is just concerned with the positioning a layer in the grid and is similar to code we've looked at previously. The undulations come from the next-to-the-last line which is the formula for a cosine wave that depends on x position, y position, and time to calculate the z position of the layer. You'll notice that the layers rock back and forth as they undulate up and down. This is accomplished by the following expression for orientation:

``````
numCol = 8; //number of columns
gap = 20; // distance between cells (pixels)
wave = 100; //wavelength in pixels
freq = 0.5; //cycles per second
damp = .5; //damping factor

x = ((index-1)%numCol)*gap;
y = Math.floor((index-1)/numCol)*gap;

xRot = Math.atan(Math.sin(x/wave + freq*Math.PI*2*time))*damp;
yRot = Math.atan(Math.sin(y/wave + freq*Math.PI*2*time))*damp;