Skip to content

Instantly share code, notes, and snippets.

@NickBeeuwsaert
Created February 12, 2013 04:10
Show Gist options
  • Save NickBeeuwsaert/4760182 to your computer and use it in GitHub Desktop.
Save NickBeeuwsaert/4760182 to your computer and use it in GitHub Desktop.
Vector. Verlet, and Linear Constraints in javascript (so I don't have to write a new one every week... :P)
function Vector(x,y){
this.x = x;
this.y = y;
};
Vector.prototype.iadd = function(x, y){
if(typeof(x)=="number"){
this.x += x;
this.y += y;
}else{
this.x += x.x;
this.y += x.y;
}
return this;
};
Vector.prototype.isub = function(x, y){
if(typeof(x)=="number"){
this.x -= x;
this.y -= y;
}else{
this.x -= x.x;
this.y -= x.y;
}
return this;
};
Vector.prototype.imul = function(x, y){
if(typeof(x)=="number"){
this.x *= x;
this.y *= y;
}else{
this.x *= x.x;
this.y *= x.y;
}
return this;
};
Vector.prototype.idiv = function(x, y){
if(typeof(x)=="number"){
this.x /= x;
this.y /= y;
}else{
this.x /= x.x;
this.y /= x.y;
}
return this;
};
Vector.prototype.add = function(x, y){
var temp = new Vector(this.x, this.y);
return temp.iadd(x, y);
};
Vector.prototype.sub = function(x, y){
var temp = new Vector(this.x, this.y);
return temp.isub(x, y);
};
Vector.prototype.mul = function(x, y){
var temp = new Vector(this.x, this.y);
return temp.imul(x, y);
};
Vector.prototype.div = function(x, y){
var temp = new Vector(this.x, this.y);
return temp.idiv(x, y);
};
Vector.prototype.set = function(x, y){
if(typeof(x)=="number"){
this.x = x;
this.y = y;
}else{
this.x = x.x;
this.y = x.y;
}
};
Vector.prototype.norm = function(){
return Math.sqrt(this.x * this.x + this.y * this.y);
};
var Verlet = function(){
Vector.apply(this, arguments);
this.previous = new Vector(this.x, this.y);
};
Verlet.prototype = Vector.prototype;
Verlet.prototype.step = function(){
var temp = this.sub(this.previous);
this.previous.set(this);
this.iadd(temp);
};
var Constraint = function(a,b,width){
this.a = a;
this.b = b;
this.width = width;
};
Constraint.prototype.constrain = function(){
var d1 = this.a.sub(this.b);
var d2 = d1.norm();
var d3 = (this.width - d2)/d2;
var d4 = d1.mul(d3*0.5, d3*0.5);
this.a.iadd(d4);
this.b.isub(d4);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment