Processing spring system
2015-11-04 Spring system
by schrodingers
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.13/processing.min.js"></script>
<canvas></canvas>
CSS
</style> <script type="text/javascript"> window.addEventListener('load', function() {
var scripts=document.body.getElementsByTagName('script');
var canvases=document.body.getElementsByTagName('canvas');
new Processing(canvases[0], scripts[0].text);
}
, false);
// Here prevent javascript in body from throwing error </script> <style>
JavaScript
/*
title: Springs
date: 2015-11-04
*/
color[] spring = {
#ff6699, #ff9900, #ffcc00, #9adb1b, #00cc66, #00cccc, #00ccff, #6633cc, #ff66cc
};
color[] flat = {
#2ecc71, #e74c3c, #3498db, #9b59b6, #f1c40f, #e67e22, #be643c, #ecf0f1, #1abc9c, #2c3e50, #f5f5f5, #bdc3c7, #7f8c8d, #95a5a6, #e0e0e0, #34495e
};
ArrayList<Spring> ps = new ArrayList();
void setup() {
size(800, 600);
smooth();
for (int i = 0; i < 50; i++){
ps.add(new Spring());
}
}
void draw() {
fill(250, 250, 250, 98);
rect(0, 0, width, height);
for (Spring s : ps){
s.display();
s.update();
}
}
class Spring {
float x, y; // rest position
float cx, cy; // current position
float vx, vy; // velocity
float rad = 20; // radius
float trad = rad; // target, changed rad
float k = 0.05; // spring constant
float damp = 0.75; // damping, oscilations deceleration
int col;
// init Spring at rest position
Spring(){
rad = random(5, 15);
trad = rad;
cx = random(rad*2, width-2*rad);
cy = random(rad*2, height-2*rad);
x = cx; // rest position == current position
y = cy;
vx = 0;
vy = 0;0
k = random(0.01, 0.02);
damp = random(0.975, 1.0);
col = spring[(int)random(0, spring.length-1)];
}
void display(){
ellipseMode(RADIUS);
noStroke();
fill(col);
ellipse(x, y, rad, rad);
}
void update() {
if (dist(mouseX, mouseY, x, y) < rad) {
vy = 1.5;
}
//float d = loc.sub(pLoc).mult(k);
//float springing = loc.sub(targetLoc);
//loc.normalize();
// loc.mult(springing);
// vel.normalize();
// vel.mult(damp);
// loc.add(vel);
//vx -= k * (x - cx); // current - rest
//vy -= k * (y - cy);
//vx *= damp;
//vy *= damp;
//x += vx;
//y += vy;
// springing force(?)
vx -= k * (rad - trad); // current - target
vy -= k * (rad - trad);
vx *= damp;
vy *= damp;
...