Created
January 22, 2012 15:56
-
-
Save christianp/1657503 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
/* | |
In Javascript, any function acts as an object constructor when you call it with the `new` keyword. | |
So, this: | |
var spring1 = new Spring(particle1, particle2, length, stiffness); | |
creates a new object which inherits all of Spring.prototype's methods and properties, and then the function Spring(..) is called on it. | |
Inside the function Spring(..), `this` refers to the newly-created object. | |
*/ | |
function Spring(particle1, particle2, length, stiffness) | |
{ | |
// Previously, you were accessing the parameters of the constructor by defining the object's methods in a closure. | |
// Store them as properties of the objects instead. | |
this.particle1 = particle1; | |
this.particle2 = particle2; | |
this.length = length; | |
this.stiffness = stiffness; | |
// you don't need to do this - use the `new` keyword wherever you call Spring() to create an instance of Spring. | |
// It automatically inherits all of Object's methods. | |
/* | |
spring = new Object(); | |
return spring; | |
*/ | |
} | |
Spring.prototype = { | |
force: function () | |
{ | |
var particle1 = this.particle1, | |
particle2 = this.particle2, | |
length = this.length; | |
stiffness = this.stiffness; | |
x = Math.sqrt(Math.pow(particle2.position.x - particle1.position.x, 2) + Math.pow(particle2.position.y - particle1.position.y, 2)) - length; | |
return stiffness * x; | |
} | |
act: function () | |
{ | |
// this.force() might change after applying the force to particle 1, depending on how it's done. | |
// Anyway, don't calculate it twice if you expect it to be the same value. | |
var force = this.force(); | |
particle1.applyforce(particle1.position.to(particle2.position).unit().scale(force)); | |
particle2.applyforce(particle2.position.to(particle1.position).unit().scale(force)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment