BNG - Rigid Collisions
by bkanber
HTML
<canvas id="canvas" height="400" width="400"></canvas>
CSS
canvas {
border:1px solid #999;
margin:10px auto;
display:block;
}
JavaScript
/*
The following is not free software. You may use it for educational purposes, but you may not redistribute or use it commercially.
(C) Burak Kanber 2012
*/
var canvas,
ctx,
height = 400,
width = 400,
stiffness = 0.5,
b = -1,
angularB = -1,
dt = 0.02;
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
Array.prototype.min = function() {
return Math.min.apply(null, this);
};
var V = function(x, y) {
this.x = x;
this.y = y;
};
V.prototype.length = function() {
return Math.sqrt(this.x*this.x + this.y*this.y);
};
V.prototype.add = function(v) {
return new V(v.x + this.x, v.y + this.y);
};
V.prototype.subtract = function(v) {
return new V(this.x - v.x, this.y - v.y);
};
V.prototype.scale = function(s) {
return new V(this.x * s, this.y * s);
};
V.prototype.dot = function(v) {
return (this.x * v.x + this.y * v.y);
};
V.prototype.cross = function(v) {
return (this.x * v.y - this.y * v.x);
};
V.prototype.toString = function() {
return '[' + this.x + ',' + this.y + ']';
};
V.prototype.rotate = function(angle, vector) {
var x = this.x - vector.x;
var y = this.y - vector.y;
var x_prime = vector.x + ((x * Math.cos(angle)) - (y * Math.sin(angle)));
var y_prime = vector.y + ((x * Math.sin(angle)) + (y * Math.cos(angle)));
return new V(x_prime, y_prime);
};
var Rect = function(x, y, w, h, m) {
if (typeof(m) === 'undefined') {
this.m = 1;
}
this.width = w;
this.height = h;
this.active = true;
this.topLeft = new V(x, y);
this.topRight = new V(x + w, y);
this.bottomRight = new V(x + w, y + h);
this.bottomLeft = new V(x, y + h);
this.v = new V(0, 0);
this.a = new V(0, 0);
this.theta = 0;
this.omega = 0;
this.alpha = 0;
this.J = this.m * (this.height * this.height + this.width * this.width) / 12000;
};
Rect.prototype.center = function() {
var diagonal =...