Ball Bounce 2
by lecollective
HTML
<canvas id="canvas" width="600" height="600" />
JavaScript
(function ($, window) {
function Vector2d(x, y) {
this.x = x;
this.y = y;
}
Vector2d.prototype.dot = function(vector) {
return this.x * vector.x + this.y * vector.y;
}
Vector2d.prototype.add = function(vector) {
return new Vector2d(this.x + vector.x, this.y + vector.y);
}
Vector2d.prototype.subtract = function(vector) {
return new Vector2d(this.x - vector.x, this.y - vector.y);
}
Vector2d.prototype.length = function() {
return Math.sqrt(this.x*this.x + this.y*this.y);
}
Vector2d.prototype.multiply = function(scaleFactor) {
return new Vector2d(this.x * scaleFactor, this.y * scaleFactor);
}
Vector2d.prototype.normalize = function() {
var len = this.length();
if (len == 0) {
this.x = 0;
this.y = 0;
return this;
} else {
this.x = this.x / len;
this.y = this.y / len;
return this;
}
}
function Ball(pos, vel, radius, mass, color) {
this.pos = pos;
this.vel = vel;
this.radius = radius;
this.color = color;
this.mass = mass;
}
Ball.prototype.render = function(ctx) {
ctx.fillStyle = this.color;
ctx.strokeStyle = this.color;
ctx.beginPath();
ctx.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI*2, false);
ctx.fill();
}
Ball.prototype.resolveCollision = function(ball) {
var delta = this.pos.subtract(ball.pos);
var r = this.radius + ball.radius;
var dist2 = delta.dot(delta);
if (dist2 > r*r) { return; /* not colliding */ }
var d = delta.length();
var mtd;
if (d != 0) {
mtd = delta.multiply(((this.radius + ball.radius)-d)/d);
} else { // special case, balls are exactly on top of eachother
...