Detecting collisions between blobs.
There are two primary methods to achieve this:
- One way is to calculate the bounding box for each blob and then check if these boxes overlap.
- Alternatively, you can render each blob on a separate offscreen canvas and utilize pixel testing to determine if they collide.
The bounding box method is quicker compared to pixel testing.
While pixel-testing may offer more accuracy, it requires greater resources and is considerably slower.
For instance:
Explanation on evaluating collisions between the bounding boxes of 2 blobs.
A demo:
http://jsfiddle.net/m1erickson/9tB7d/
Initiate with a Kinetic Blob
var blueBlob = new Kinetic.Line({
points: [73,140,340,23,500,109,300,170],
stroke: 'blue',
strokeWidth: 10,
fill: '#aaf',
tension: 0.8,
closed: true
});
This particular blob comprises multiple Bezier curves.
Extract the Bezier curves composing the blob:
function kineticBlob2Beziers(blob){
var beziers=[];
var start=blob.getPoints();
var pts=blob.getTensionPoints();
var n=0;
var lastN=pts.length-2;
var sx=start[0];
var sy=start[1];
while(n<lastN){
bez={
s: {x:sx,y:sy},
c1:{x:pts[n++],y:pts[n++]},
c2:{x:pts[n++],y:pts[n++]},
e: {x:pts[n++],y:pts[n++]}
};
beziers.push(bez);
sx=pts[n-2];
sy=pts[n-1];
}
return(beziers);
}
Determine the bounding box of the blob using its Bezier curves:
function getBlobBB(beziers){
var minX=1000000;
var minY=1000000;
var maxX=-1000000;
var maxY=-1000000;
for(var i=0;i<beziers.length;i++){
var bez=beziers[i];
for(var t=0.00;t<=1.00;t+=.01){
var pt=getCubicBezierXYatT(bez.s,bez.c1,bez.c2,bez.e,t);
if(pt.x<minX){minX=pt.x;}
if(pt.x>maxX){maxX=pt.x;}
if(pt.y<minY){minY=pt.y;}
if(pt.y>maxY){maxY=pt.y;}
}
}
return({x:minX,y:minY,width:maxX-minX,height:maxY-minY});
}
function getCubicBezierXYatT(startPt,controlPt1,controlPt2,endPt,T){
var x=CubicN(T,startPt.x,controlPt1.x,controlPt2.x,endPt.x);
var y=CubicN(T,startPt.y,controlPt1.y,controlPt2.y,endPt.y);
return({x:x,y:y});
}
// cubic helper formula at T distance
function CubicN(T, a,b,c,d) {
var t2 = T * T;
var t3 = t2 * T;
return a + (-a * 3 + T * (3 * a - a * T)) * T
+ (3 * b + T * (-6 * b + b * 3 * T)) * T
+ (c * 3 - c * 3 * T) * t2
+ d * t3;
}
Check for collision between two bounding boxes (rectangles):
function Colliding(left1,top1,right1,bottom1,left2,top2,right2,bottom2){
return(!(
left1 > right2 ||
right1 < left2 ||
bottom1 < top2 ||
top1 >bottom2
));
}