I am trying to do a simple collision detection test for two convex shapes. My shapes are defined as bellow
var convex2 = [
{x:-0.1, y:-0.1},
{x: 0.12, y:-0.07},
{x: 0.22, y:0.0},
{x: 0.0, y:0.2},
{x:-0.1, y:0.12}
];
var convex = [
{x:-0.08, y:-0.07},
{x: 0.07, y:-0.06},
{x: 0.09, y: 0.08},
{x:-0.07, y: 0.09},
];
I have a function to check if two polygons collide each other and calling it
convexConvex(convex, convex2)
Below is my attempt to implement SPT
Firstly, I am a beginner in Javascript so please let me know if am doing something wrong syntax wise.
I have defined the projection axis to be horizontal x-axis (1,0). I am not sure if that is right.
The function always returns true even they are not colliding. What am I doing wrong?
function convexConvex(p1, p2) {
//TODO
var axis = {x:1,y:0};
var p2MaxValue = Number.NEGATIVE_INFINITY;
var p2MinValue = Number.POSITIVE_INFINITY;
var p1MaxValue = Number.NEGATIVE_INFINITY;
var p1MinValue = Number.POSITIVE_INFINITY;
var p2MaxPoint; //Max point for P2
var p2MinPoint; //Min point for P2
var p1MaxPoint; //Max point for p1
var p1MinPoint; //Min point for p1
//find min and max points in shape p2
for(var i in p2)
{
var dotProduct = p2[i].x*axis.x + p2[i].y*axis.y;
if(dotProduct > p2MaxValue)
{
p2MaxValue = dotProduct;
p2MaxPoint = p2[i];
}
if(dotProduct < p2MinValue)
{
p2MinValue = dotProduct;
p2MinPoint = p2[i];
}
}
//find min and max points in shape p1
for(var i in p1)
{
var dotProduct = p1[i].x*axis.x + p1[i].y*axis.y;
if(dotProduct > p1MaxValue)
{
p1MaxValue = dotProduct;
p1MaxPoint = p1[i];
}
if(dotProduct < p1MinValue)
{
p1MinValue = dotProduct;
p1MinPoint = p1[i];
}
}
//compare the min and max projection values
if(p2MinValue < p1MaxValue || p2MaxValue < p1MinValue)
return true
return false;
}