我正在尝试编写自己的分离轴定理实现,但我很难让它像我想要的那样准确地工作。我不能肯定地说,但是当形状周围的一个假想的盒子像第一个形状一样碰撞时,它看起来像是在说发生了碰撞。但是第二种形状完美地工作。
这是正方形的顶点数据(精确坐标):
vertsx = [ 200, 220, 220, 200 ]
vertsy = [ 220, 220, 200, 200 ]
这是测试形状 1 的顶点数据(相对于鼠标):
vertsx = [ -10, 0, 10, 10, -10 ]
vertsy = [ -10, -50, -10, 10, 10 ]
最后是测试形状 2(相对于鼠标)的顶点数据:
vertsx = [ -10, 0, 10, 10, -10 ]
vertsy = [ -10, -20, -10, 10, 10 ]
只是为了澄清,翻译后的坐标是经过测试的坐标,并且这些坐标的形状已经按照所示的坐标顺序进行了测试。
这是实际的功能。
function collisionConvexPolygon ( vertsax, vertsay, vertsbx, vertsby ) {
var alen = vertsax.length;
var blen = vertsbx.length;
// Loop for axes in Shape A
for ( var i = 0, j = alen - 1; i < alen; j = i++ ) {
// Get the axis
var vx = vertsax[ j ] - vertsax[ i ];
var vy = -( vertsay[ j ] - vertsay[ i ] );
var len = Math.sqrt( vx * vx + vy * vy );
vx /= len;
vy /= len;
// Project shape A
var max0 = vertsax[ 0 ] * vx + vertsay[ 0 ] * vy, min0 = max0;
for ( k = 1; k < alen; k++ ) {
var proja = vertsax[ k ] * vx + vertsay[ k ] * vy;
if ( proja > max0 ) {
max0 = proja;
}
else if ( proja < min0 ) {
min0 = proja;
}
}
// Project shape B
var max1 = vertsbx[ 0 ] * vx + vertsby[ 0 ] * vy, min1 = max1;
for ( var k = 1; k < blen; k++ ) {
var projb = vertsbx[ k ] * vx + vertsby[ k ] * vy;
if ( projb > max1 ) {
max1 = projb;
}
else if ( projb < min1 ) {
min1 = projb;
}
}
// Test for gaps
if ( !axisOverlap( min0, max0, min1, max1 ) ) {
return false;
}
}
// Loop for axes in Shape B (same as above)
for ( var i = 0, j = blen - 1; i < blen; j = i++ ) {
var vx = vertsbx[ j ] - vertsbx[ i ];
var vy = -( vertsby[ j ] - vertsby[ i ] );
var len = Math.sqrt( vx * vx + vy * vy );
vx /= len;
vy /= len;
var max0 = vertsax[ 0 ] * vx + vertsay[ 0 ] * vy, min0 = max0;
for ( k = 1; k < alen; k++ ) {
var proja = vertsax[ k ] * vx + vertsay[ k ] * vy;
if ( proja > max0 ) {
max0 = proja;
}
else if ( proja < min0 ) {
min0 = proja;
}
}
var max1 = vertsbx[ 0 ] * vx + vertsby[ 0 ] * vy, min1 = max1;
for ( var k = 1; k < blen; k++ ) {
var projb = vertsbx[ k ] * vx + vertsby[ k ] * vy;
if ( projb > max1 ) {
max1 = projb;
}
else if ( projb < min1 ) {
min1 = projb;
}
}
if ( !axisOverlap( min0, max0, min1, max1 ) ) {
return false;
}
}
return true;
}
如果你需要我会尝试其他形状。
这是我的axisOverlap
功能。
function axisOverlap ( a0, a1, b0, b1 ) {
return !( a0 > b1 || b0 > a1 );
}