Canvas multiple collision
HTML
<canvas id="canvas" width="500" height="400" style="border:1px solid #000000;"></canvas>
JavaScript
// get the theory behind:
// http://nepraunig.com/wp/?p=207
// grab the canvas and context
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// the shape object is a placeholder for all squares
// we are going to create
var Shape = function(x, y, width, height, vX, vY, aX, aY) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.vX = vX;
this.vY = vY;
this.aX = aX;
this.aY = aY;
};
// all shapes will be stored in an array
// so they can be accessed easily
var shapes = new Array();
// creating 10 shapes with different x, y values,
// width and height and speed
for (var i = 0; i < 50; i++) {
var x = Math.random()*250+50;
var y = Math.random()*250+50;
var width = Math.random()*20+1;
var height = width;
var vX = Math.random()*5+1;
var aX = Math.random()*0.4;
// for demonstration purposes movement just in x-direction
var vY = 0;
var aY = 0;
shapes.push(new Shape(x, y, width, height, vX, vY, aX, aY));
}
function animate() {
// clear
ctx.clearRect(0, 0, canvas.width, canvas.height);
// loop through all the shapes and manipulate their x-values
var shapesLength = shapes.length;
for (var i = 0; i < shapesLength; i++) {
var tmpShape = shapes[i];
moveShape(tmpShape);
// if one shape leaves the canvas, put it back on the left edge
// recalculate the speed variable so that it gets more "random"
if(tmpShape.x > 500) {
resetShape(tmpShape);
}
// collision detection against all other shapes
// start from the next shape than the actual
for(var j = i+1; j < shapesLength; j++) {
var checkShape = shapes[j];
if ( !( checkShape.x + checkShape.width < tmpShape.x ) &&
!( tmpShape.x + tmpShape.width < checkShape.x) &&
!( checkShape.y + checkShape.height < tmpShape.y) &&
...