2015-02-08 67 views
0

我正試圖爲兩個凸形狀做一個簡單的碰撞檢測測試。我的形狀被定義爲波紋管Javascript中的分離軸定理實現

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; 
} 

回答