Created
October 22, 2013 05:37
-
-
Save ohmygodwin/7095689 to your computer and use it in GitHub Desktop.
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
import toxi.physics2d.*; | |
import toxi.physics2d.behaviors.*; | |
import toxi.geom.*; | |
VerletPhysics2D physics; | |
Chain chain, chain2, chain3; | |
void setup() { | |
size(662, 331); | |
smooth(); | |
physics=new VerletPhysics2D(); | |
physics.addBehavior(new GravityBehavior(new Vec2D(0,0.1))); | |
physics.setWorldBounds(new Rect(0,0,width,height)); | |
chain = new Chain(300,20,30,0.2, width/2); | |
} | |
void draw() { | |
background(0); | |
physics.update(); | |
chain.updateTail(mouseX,mouseY); | |
chain.display(); | |
} | |
void mousePressed() { | |
chain.contains(mouseX,mouseY); | |
} | |
void mouseReleased() { | |
chain.release(); | |
} | |
// The Nature of Code | |
// <http://www.shiffman.net/teaching/nature> | |
// Spring 2010 | |
// Toxiclibs example | |
// A soft pendulum (series of connected springs) | |
class Chain { | |
float totalLength; // How long | |
int numPoints; // How many points | |
float strength; // Strength of springs | |
float radius; // Radius of ball at tail | |
float xpos; // x position of head | |
VerletParticle2D tail; | |
PVector offset = new PVector(); | |
boolean dragged = false; | |
Chain(float l, int n, float r, float s, float x) { | |
totalLength = l; | |
numPoints = n; | |
radius = r; | |
strength = s; | |
xpos = x; | |
float len = totalLength / numPoints; | |
for(int i=0; i < numPoints; i++) { | |
VerletParticle2D particle=new VerletParticle2D(xpos,i*len); | |
physics.addParticle(particle); | |
if (i>0) { | |
VerletParticle2D previous = physics.particles.get(i-1); | |
VerletSpring2D spring=new VerletSpring2D(particle,previous,len,strength); | |
physics.addSpring(spring); | |
} | |
} | |
VerletParticle2D head=physics.particles.get(0); | |
head.lock(); | |
tail = physics.particles.get(numPoints-1); | |
tail.lock(); | |
} | |
void contains(int x, int y) { | |
for (int i = 5; i < numPoints; i++) { | |
VerletParticle2D current = physics.particles.get(i); | |
float d = dist(x,y,current.x,current.y); | |
if (d < radius) { | |
offset.x = tail.x - x; | |
offset.y = tail.y - y; | |
tail.lock(); | |
dragged = true; | |
} | |
} | |
} | |
void release() { | |
dragged = false; | |
} | |
void updateTail(int x, int y) { | |
if (dragged) { | |
tail.set(x+offset.x,y+offset.y); | |
} | |
} | |
void display() { | |
for(int i=0; i < physics.particles.size()-1; i++) { | |
VerletParticle2D p1 = physics.particles.get(i); | |
VerletParticle2D p2 = physics.particles.get(i+1); | |
stroke(255); | |
line(p1.x,p1.y,p2.x,p2.y); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment