JSFiddle - React, Tailwind, and code Playground
HTML
This is a demo of a Javascript BoundingBox collision class.
<p />
<div id='box' />
CSS
div { border:1px solid black; position:absolute; }
#box {background:#def;width:310px; height:310px}
JavaScript
// BoundingBox
function BoundingBox(x,y,w,h) {
this.x = x;
this.y = y;
this.w = w || 0.1;
this.h = h || 0.1;
};
BoundingBox.prototype.intersects = function(otherbb) {
return (this.x + this.w > otherbb.x &&
this.x < otherbb.x + otherbb.w &&
this.y + this.h > otherbb.y &&
this.y < otherbb.y + otherbb.h);
};
// ArrayContainer
function ArrayContainer() { this.items = []; };
ArrayContainer.prototype.add = function(bb) { this.items.push(bb); };
ArrayContainer.prototype.remove = function(bb) {
for(var i = this.items.length; i-->0; )
if (this.items[i] === bb)
return this.items.splice(i,1);
};
ArrayContainer.prototype.getIntersections = function() {
intersections = [];
var items = this.items;
for(var i=items.length; i-->0; )
for(var j=i-1; j--> 0;)
if (items[i].intersects(items[j]))
intersections.push([items[i], items[j]]);
return intersections;
};
// demo
var r = Math.random;
var allMyObjects = new ArrayContainer();
for(var i=0; i<100; i++)
allMyObjects.add(new BoundingBox(r()*300, r()*300, 10, 10));
var startTime = +new Date();
var intersections = allMyObjects.getIntersections();
console.log('getIntersections took', new Date()-startTime);
// display collisions on page!
for(var i=0; i<intersections.length; i++) {
var pair = intersections[i];
pair[0].collision = pair[1].collision = 1;
}
$(allMyObjects.items).each(function() {
var bb = this;
$("<div> </div>").
css({top:bb.x,left:bb.y,width:bb.w,height:bb.h }).
css({borderColor:bb.collision ?'red':null })
.appendTo('#box');
});