Collision algorithm built into my work in progress map engine, I could add more shape types in the future - for now does rectangles and circles:
static polysCollide(x, y, _one, two)
{
let result = false;
let one = {x: _one.x + x, y:_one.y + y, type: _one.type, w:_one.w, h:_one.h};
if(one.type === 0)
{
if(two.type === 0)
{//circle with circle
result = (((one.x - two.x) * (one.x - two.x) + (one.y - two.y) * (one.y - two.y)) <= ((one.w + two.w) * (one.w + two.w)));
}
else if(two.type === 1)
{//circle with rect
let x_d = one.x - two.x - two.w /2;
x_d = x_d < 0 ? -x_d : x_d;
let y_d = one.y - two.y - two.h /2;
y_d = y_d < 0 ? -y_d : y_d;
if((x_d > (two.w/2 + one.w)) || (y_d > (two.h/2 + one.w)))
{//distance between centres > radius + half width or height of square
result = false;
}
else
{
if(x_d <= two.w/2 || y_d <= two.h/2)
{//distance between centres < half width or height of square (combined with check above)
result = true;
}
else
{//final check pythag
x_d = x_d - two.w/2;
y_d = y_d - two.h/2;
result = ((x_d * x_d + y_d * y_d) <= one.w * one.w);
}
}
}
else
{
CEngine.error ("Unknown polygon type given to collision engine, valid types are 0 or 1, supplied type was " + two.type);
}
}
else if(one.type === 1)
{
if(two.type === 0)
{//circle with rect
let x_d = two.x - one.x - one.w /2;
x_d = x_d < 0 ? -x_d : x_d;
let y_d = two.y - one.y - one.h /2;
y_d = y_d < 0 ? -y_d : y_d;
if((x_d > (one.w/2 + two.w)) || (y_d > (one.h/2 + two.w)))
{//distance between centres > radius + half width or height of square
result = false;
}
else
{
if(x_d <= one.w/2 || y_d <= one.h/2)
{//distance between centres < half width or height of square (combined with check above)
result = true;
}
else
{//final check pythag
x_d = x_d - one.w/2;
y_d = y_d - one.h/2;
result = ((x_d * x_d + y_d * y_d) <= two.w * two.w);
}
}
}
else if(two.type === 1)
{//rect with rect
result = (
(one.x <= (two.x + two.w)) &&
((one.x + one.w) >= two.x) &&
(one.y <= (two.y + two.h)) &&
((one.y + one.h) >= two.y));
}
else
{
CEngine.error ("Unknown polygon type given to collision engine, valid types are 0 or 1, supplied type was " + two.type);
}
}