topical media & game development
graphic-processing-algorithm-Ch06-p145-p145.pde / pde
float M = 0.8; // Mass
float K = 0.2; // Spring constant
float D = 0.92; // Damping
float R = 100; // Rest position
float ypos; // Position
float v = 0.0; // Velocity
float a = 0; // Acceleration
float f = 0; // Force
boolean released = false;
void setup() {
size(200, 200);
ypos = height/2;
}
void draw() {
background(200);
if(released)move();
ellipse(width/2, ypos , 50,50);
}
void move(){
f = -K * (ypos - R); // f=-ky
a = f / M; // Set the acceleration, f=ma == a=f/m
v = D * (v + a); // Set the velocity
ypos += v; // Updated position
if(abs(v) < 0.01) {
v = 0.0;
released = false;
}
}
void mouseMoved() {
if(dist(mouseX,mouseY,width/2,ypos)<50)
stroke(255,0,0);
else
stroke(0);
}
void mouseDragged() {
released = false;
ypos = mouseY;
}
void mouseReleased(){
released = true;
}
(C) Æliens
04/09/2009
You may not copy or print any of this material without explicit permission of the author or the publisher.
In case of other copyright issues, contact the author.