我正在尝试对两个凸形进行简单的碰撞检测测试。我的形状定义如下
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},
];
我有一个函数来检查两个多边形是否相互碰撞并调用它
convexConvex(convex, convex2)
以下是我实施 SPT 的尝试
首先,我是 Javascript 的初学者,所以如果我在语法上做错了,请告诉我。
我已将投影轴定义为水平 x 轴 (1,0)。我不确定这是否正确。
即使它们没有碰撞,该函数也始终返回 true。我究竟做错了什么?
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;
}