Created
October 19, 2017 21:03
-
-
Save golanlevin/8e0ab2c2b6818d0e8a08f9c20c086ef7 to your computer and use it in GitHub Desktop.
A Spring in Processing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A basic spring in Processing, based on: | |
// Hooke's law: F = -kx | |
// Newton's law: F = ma | |
// For more examples, see this lecture: | |
// http://cmuems.com/2015c/deliverables/deliverables-10/springs/ | |
float restLength; | |
float vx; | |
float px; | |
void setup() { | |
size(600, 400); | |
restLength = 100; | |
vx = 0; | |
px = 0; | |
} | |
void draw() { | |
background(255); | |
float k = 0.1; | |
float mass = 1.0; | |
float damping = 0.98; | |
if (mousePressed) { | |
px = mouseX - restLength; | |
} else { | |
float fx = -k * px; // Hooke's law | |
float ax = fx / mass; // Newton's law | |
vx = vx + ax; | |
vx = vx * damping; | |
px = px + vx; | |
} | |
drawSpring(); | |
drawDebug(); | |
} | |
void drawSpring() { | |
fill(128); | |
stroke(0); | |
strokeWeight(3); | |
ellipse(restLength + px, 200, 30, 30); | |
line(0, 200, restLength + px, 200); | |
} | |
void drawDebug() { | |
strokeWeight(1); | |
stroke(100); | |
line(restLength, 0, restLength, height); | |
line(restLength, mouseY-30, restLength+px, mouseY-30); | |
text("Displacement: " + (int)(px), mouseX+10, mouseY-30); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment