Skip to content

Instantly share code, notes, and snippets.

@cosinekitty
Created November 27, 2019 02:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cosinekitty/b38ac2e1fda4108eabfa18ff0b3b6f38 to your computer and use it in GitHub Desktop.
Save cosinekitty/b38ac2e1fda4108eabfa18ff0b3b6f38 to your computer and use it in GitHub Desktop.
AddForce() {
// Calculate the length of the spring.
const dx = this.ball2.x - this.ball1.x;
const dy = this.ball2.y - this.ball1.y;
const len = Math.sqrt(dx*dx + dy*dy);
// The difference between the spring's rest length and its current length
// tells how much it is stretched or compressed.
// Multiply by the spring constant to get the magnitude of the force.
const displacement = len - this.restLength;
const force = this.springConst * displacement;
// Safety valve: if two balls are at the same location, we avoid division by zero.
if (Math.abs(len) >= 1.0e-6) {
// Calculate force vector = force magnitude * directional unit vector
const fx = force * (dx / len);
const fy = force * (dy / len);
// Add equal and opposite forces to the two connected balls.
this.ball1.fx += fx;
this.ball1.fy += fy;
this.ball2.fx -= fx;
this.ball2.fy -= fy;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment