div collision detection
moving a bunch of divs and detecting if any collide with each other
by Jimm P
HTML
<div id="container"></div>
CSS
div#container {
height: 300px;
width: 300px;
background-color: lightgrey;
}
#container > div {
width: 10px;
height: 10px;
background-color:yellow;
position:fixed;
}
JavaScript
$(document).ready(function () {
// get numberOfObjects and pass to addObjects()
numberOfObjects = 10;
addObjects(numberOfObjects);
});
function addObjects(numberOfObjects) {
// dynamically add objects to parent div
// give each a unique class name
console.log('creating ' + numberOfObjects + ' objects now...');
for (i = 0; i < numberOfObjects; i++) {
$("#container").append('<div class="object' + i + '"></a>');
}
console.log('animating ' + numberOfObjects + ' objects now...');
for (i = 0; i < numberOfObjects; i++) {
animateDiv($('.object' + i));
}
}
function makeNewPosition($container) {
// Get viewport dimensions (remove the dimension of the div)
var h = $container.height() - 50;
var w = $container.width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv($target) {
var newq = makeNewPosition($target.parent());
var oldq = $target.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$target.animate({
top: newq[0],
left: newq[1]
}, speed, function () {
animateDiv($target);
});
}
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.1;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}