Professional Documents
Culture Documents
Mass Spring
Mass Spring
// do the animation
while (true) {
// clear all the forces
double[] fx = new double[N];
double[] fy = new double[N];
// spring forces act between every pairing of particles
// spring force is proportional to the difference between the rest length of
the spring
// and the distance between the 2 particles it's acting on
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (i == j) continue;
// calculate distance between particles i and j
double dx = rx[j] - rx[i];
double dy = ry[j] - ry[i];
double length = Math.sqrt(dx*dx + dy*dy);
// figure out the force
double force = springStrength * (length - springLength);
double springForceX = force * dx / length;
double springForceY = force * dy / length;
// clear
StdDraw.clear();
// draw everything
for (int i = 0; i < N; i++) {
// draw a circle for each node
StdDraw.filledCircle(rx[i], ry[i], 1.0);
// draw the connections between every 2 nodes
for (int j = 0; j < i; j++) {
StdDraw.line(rx[i], ry[i], rx[j], ry[j]);
}
}
// show and wait
StdDraw.show(10);
}
}