Created
November 27, 2019 02:22
-
-
Save cosinekitty/b38ac2e1fda4108eabfa18ff0b3b6f38 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
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