Last active
November 27, 2019 02:16
-
-
Save cosinekitty/f0d3b078b2b1920ab342fb7cf6ac296e 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
Update(dt) { | |
var b, s; | |
// Calculate the force vectors acting on all the balls: | |
// both from springs and from gravity. | |
// Start out with just the gravitational force on each ball. | |
for (b of this.ballList) { | |
b.fx = 0.0; | |
b.fy = b.mass * this.gravity; | |
} | |
// Go through all the springs and calculate | |
// the forces on the balls connected to their endpoints. | |
// There will be equal and opposite forces on each pair. | |
for (s of this.springList) { | |
s.AddForce(); | |
} | |
// Now all the forces are correct. | |
// Use the forces to update the position and speed of each ball. | |
const friction = Math.pow(0.5, dt / FrictionHalfLifeSeconds); | |
for (b of this.ballList) { | |
if (b.anchor === 0) { // skip anchors, because they don't move | |
// F = ma, therefore a = dv/dt = F/m. | |
// dv = dt * F/m | |
let dvx = dt * b.fx/b.mass; | |
let dvy = dt * b.fy/b.mass; | |
// Update the position using the mean speed in this increment. | |
b.x += dt * (b.vx + dvx/2.0); | |
b.y += dt * (b.vy + dvy/2.0); | |
// Update the ball's speed. Apply friction to gradually reduce energy. | |
b.vx = (friction * b.vx) + dvx; | |
b.vy = (friction * b.vy) + dvy; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment