BNG - Rigid 1
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 = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
height = 400,
width = 400,
stiffness = 0.5,
b = -1,
angularB = -7,
dt = 0.02;
/* A more generic vector class could take an arbitrary number of elements, rather than just x, y, or z. This vector class is strictly 2D */
var V = function(x, y) {
this.x = x;
this.y = 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);
};
/* Normally the vector cross product function returns a vector. But since we know that all our vectors will only be 2D (x and y only), any cross product we calculate will only have a z-component. Since we don't have a 3D vector class, let's just return the z-component as a scalar. We know that the x and y components will be zero. This is absolutely not the case for 3D. */
V.prototype.cross = function(v) {
return (this.x * v.y - this.y * v.x);
};
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);
};
/* Our simple rectangle class is defined by the coordinates of the top-left corner, the width, height, and mass. */
var Rect = function(x, y, w, h, m) {
if (typeof(m) === 'undefined') {
this.m = 1;
}
this.width = w;
this.height = h;
this.topLeft = new V(x, y);
this.topRight = new V(x + w, y);
this.bottomRight = new V(x + w,...