Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Ira Greenberg
class Boundary {
private float lower;
private float upper;
Boundary(float lower, float upper) {
this.lower = lower;
this.upper = upper;
}
float lower() {
return lower;
}
float upper() {
return upper;
}
boolean exclude(float val) {
if (val < lower) {
return true;
}
return val > upper;
}
}
/**
* Verlet Integration - ragdoll chain
* Pos = pos + (pos-posOld)
* alternative to x += speed
* -with free rotational velocity
*/
int particles = 5;
VerletBall[] balls = new VerletBall[particles];
int bonds = particles-1;
VerletStick[] sticks = new VerletStick[bonds];
void setup() {
size(400, 400);
float shapeR = 40;
float tension = .05;
for (int i=0; i<particles; i++) {
PVector push = new PVector(random(3, 6.5), random(3, 6.5));
PVector p = new PVector(width/2+shapeR*i, height/2);
balls[i] = new VerletBall(p, push, 5);
if (i == 0) { continue; }
sticks[i-1] = new VerletStick(balls[i-1], balls[i], tension);
}
}
void draw() {
background(255);
for (VerletStick stick : sticks) {
stick.render();
stick.constrainLen();
}
for (VerletBall ball: balls) {
ball.verlet();
ball.render();
ball.boundsCollision();
}
}
class VerletBall {
PVector pos, posOld;
PVector push;
float radius;
Boundary xBounds;
Boundary yBounds;
VerletBall(){
}
VerletBall(PVector pos, PVector push, float radius){
this.pos = pos;
this.push = push;
this.radius = radius;
xBounds = new Boundary(radius, width - radius);
yBounds = new Boundary(radius, height - radius);
this.posOld = pos.copy();
// start motion
pos.add(push);
}
void verlet(){
PVector posTemp = pos.copy();
pos.x += (pos.x-posOld.x);
pos.y += (pos.y-posOld.y);
posOld.set(posTemp);
}
void render(){
ellipse(pos.x, pos.y, radius*2, radius*2);
}
void boundsCollision(){
if (xBounds.exclude(pos.x)){
posOld.x = constrain(pos.x, xBounds.lower(), xBounds.upper());
pos.x = (pos.x <= radius)? posOld.x + push.x : posOld.x - push.x;
}
if (yBounds.exclude(pos.y)){
posOld.y = constrain(pos.y, yBounds.lower(), yBounds.upper());
pos.y = (pos.y <= radius)? posOld.y + push.y : posOld.y - push.y;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment