Skip to content

Instantly share code, notes, and snippets.

@laustdeleuran
Created October 19, 2016 03:33
Show Gist options
  • Save laustdeleuran/ea837386447f8b6a538b4cd43a816f5b to your computer and use it in GitHub Desktop.
Save laustdeleuran/ea837386447f8b6a538b4cd43a816f5b to your computer and use it in GitHub Desktop.
Bouncing sine wave in Processing
/**
* @overview Bouncing sine wave
* @author ljd
* @source http://codepen.io/laustdeleuran/pen/GjBwKm
*/
/**
* @class Sine
*/
class Sine {
// Class props. These can be changed to change wave appearance. TODO: Add getter / setter for relevant props.
color clr = color(165, 255, 228);
float hertz = 1;
int speed = 1;
float amplitude = 1;
float start = 0;
float stop = 1;
int noise = 50;
float xPos;
float yPos;
/**
* @constructor
*/
Sine() {
strokeWeight(3);
}
/**
* @method
* @desc
* Draw sine wave at time
*
* @param {number} time
*/
void draw(float time) {
float waveHeight = HEIGHT * amplitude * HEIGHT_BOUNDARY;
float xStart = WIDTH * start;
float xStop = WIDTH * stop;
time *= speed;
float dist = abs(xStop - xStart);
float halfWaveLength = WIDTH / hertz / 2;
float ratio = dist / halfWaveLength;
float dissonance = (0.5 - abs(0.5 - (ratio - floor(ratio)))) * 2;
for (int i = 0; i <= dist*2; i++) {
float realNoise = random(-0.5, 0.5) * noise * dissonance;
float y = sin(i / WIDTH * TWO_PI * hertz + time) * waveHeight / 2 + HEIGHT / 2 + realNoise;
float x = i < dist ? xStart + i : xStop - (i - dist);
// Only draw on second round or later, since we need two points.
if (x > 0) {
line(xPos, yPos, x, y);
stroke(clr);
}
xPos = x;
yPos = y;
}
}
}
/**
* Instantiate globals
*/
final float HEIGHT = 600;
final float WIDTH = 600;
final float HEIGHT_BOUNDARY = 0.9;
float time = 0;
Sine wave;
/**
* @setup
**/
void setup() {
size(600, 600); // Would like to pass globals here, but Processing doesn't allow that (wtf)
wave = new Sine();
}
/**
* @draw
**/
void draw() {
background(0);
wave.draw(time);
time += 0.01; // Is there a better way to track time?
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment