/* Our wave class contains all the properties and methods necessary for calculating and drawing a cosine or sine wave. */ class Wave { /* To make it easy to select a sin or cosine wave, we define two 'constants' that we can access outside and inside of the class. From outside of the class we can access these with: Wave.SIN or Wave.COS, inside the class we can refer directly to SIN and COS */ public static final int SIN = 1; public static final int COS = 2; // The spacing and width of our wave int xspacing; int waveWidth; // Is this a COS or SIN wave int type; // Our wave is calculated with the theta, amplitude and period of the // wave form float theta; float amplitude; float period; // The distance between wave samples float dx; // The height of our wave at different sample points float[] yvalues; // Create a new wave with a specified type, amplitude and period Wave(int type_, float amp_, float period_) { type = type_; amplitude = amp_; period = period_; } /* Where our previous Wave class calculated our sizing and yvalues array in the constructor, this version of the Wave class has a separate method for setting the spacing and width of the wave, so that the WaveCollection can directly set the values */ void setSizing(int xspace, int width_) { // use the spacing values to calculate our // other properties waveWidth = width_; xspacing = xspace; dx = (TWO_PI / period) * xspacing; yvalues = new float[waveWidth / xspacing]; } /* The calcWave method will recalculate the height of our wave samples */ void calcWave() { theta += 0.01; float x = theta; for (int i = 0; i < yvalues.length; i++) { if (type == SIN) yvalues[i] = sin(x) * amplitude; if (type == COS) yvalues[i] = cos(x) * amplitude; x += dx; } } /* Draw our wave to the screen, using the appropriate spacing, referencing the height values calculated using the calcWave method */ void render() { smooth(); for (int x = 0; x < yvalues.length; x++) { noStroke(); fill(32, 64, 128, 50); ellipseMode(CENTER); ellipse(x * xspacing, yvalues[x], 16, 16); } } /* Access the height values we've calculated */ float[] getValues() { return yvalues; } }