2015-05-13 112 views
0

最近我一直在使用多邊形類來創建小行星以及子彈和飛船。我目前正在嘗試爲程序創建碰撞檢測,但似乎碰撞檢測只能在1/5左右的時間內工作(沒有出現任何模式表明它爲什麼工作)。的Java 2D多邊形 - 多邊形碰撞檢測

下面的代碼.. 創建多邊形:

void renderPoly() { 
    int j; 
    int s = sides; 
    double r, angle; 
    int x, y; 

    for (j = 0; j < s; j++) { 
     angle = 2 * Math.PI/s * j; 
     r = MIN_ROCK_SIZE + (int) (Math.random() * (MAX_ROCK_SIZE - MIN_ROCK_SIZE)); 
     x = (int) (r * Math.cos(angle)); 
     y = (int) (r * -Math.sin(angle)); 

     cOM[0] += x; 
     cOM[1] += y; 
     pointData[j][0] = x; 
     pointData[j][1] = y; 
    } 

    cOM[0] /= asteroidShape.npoints; 
    cOM[1] /= asteroidShape.npoints; 

    for (int i = 0; i < asteroidShape.npoints; i++) { 
     pointData[i][0] += cOM[0]; 
     pointData[i][1] += cOM[1]; 
    }  
} 

旋轉和移動的多邊形:

void move() {  
    int x, y, i; 
    //change rotation 
    theta += rotVel; 

    //change x 
    asteroidData[0] += deltaX; 

    //change y 
    asteroidData[1] += deltaY; 

    for (i = 0; i < asteroidShape.npoints; i++) { 

     x = (int) (pointData[i][0] * Math.cos(theta) - pointData[i][1] * Math.sin(theta)); 
     y = (int) (pointData[i][0] * Math.sin(theta) + pointData[i][1] * Math.cos(theta)); 

     asteroidShape.xpoints[i] = x + asteroidData[0]; 
     asteroidShape.ypoints[i] = y + asteroidData[1]; 

     asteroidShape.invalidate(); 
    } 
} 

檢查,如果感人子彈:

boolean hitBullet(Bullet b) { 
    this.asteroidShape.invalidate(); 
    for (int i = 0; i < b.bulletShape.npoints; i++) 
     if (this.asteroidShape.contains(b.bulletShape.xpoints[i], b.bulletShape.ypoints[i])) 
      return true; 

    for (int j = 0; j < this.asteroidShape.npoints; j++) 
     if (b.bulletShape.contains(this.asteroidShape.xpoints[j], this.asteroidShape.ypoints[j])) 
      return true; 

    return false; 

} 

(船方法是相同的,除了構造函數需要一個船對象)

以及調用它的「遊戲」類環:

for (int i = 0; i < aArray.length-1; i++) { 
    if (aArray[i] != null) { 

     for (int j = 0; j < bArray.length-1; j++) { 
      if (bArray[j] != null) { 

       if (aArray[i].hitBullet(bArray[j])) { 
        aArray[i] = null; 
        bArray[j] = null; 
        i = aArray.length-1; 
        j = bArray.length-1; 
       } 

      } 
      else { 
       i = aArray.length-1; 
       j = bArray.length-1; 
      } 
     } 

    } 
    else { 
     i = aArray.length-1; 
    } 
} 

我已經在替代解決方案,比如分離軸定理一直在尋找周圍然而,我在次,並自具有凸多邊形這個方法(.contains())已經存在了,我想用它。

任何幫助將不勝感激,謝謝!

回答

1

解決此問題的最簡單方法是將Shapes(在您的案例中是Polygon(2D?))轉換爲Areas。您可以使用Area.intersect(區),看看如果兩個區域相撞

+1

根據該文件的Area.intersect(區)有兩個方面,並提出它們放在一起。它不檢查它們是否相交。 Area.intersects()方法需要一個2D矩形,而不是另一個區域。所以這與Polygon類相同。 我也用區域替換了多邊形,並繼續使用.contains但它具有山姆效應 – user3057800

+0

同樣,這也不起作用.. 'Area asteroid = new Area(asteroidShape); if(asteroid.intersects(c.pgn.getBounds2D())) return true;' – user3057800

+0

if(area1.intersect(area2).equals(new Area())這意味着兩個形狀沒有碰撞(有沒有共同的區域) – ControlAltDel