2015-01-01 40 views
2

我正在研究Java 2D視頻遊戲,我正在尋找比您在下面看到的更快的碰撞檢測算法。我正試圖檢測魚雷和船之間的碰撞。我正在使用的算法嚴重影響我的主要圖形2D調度循環的性能,減緩我的屏幕重繪。想知道是否有人可以推薦一個更好的算法來處理這個問題,這樣可以更快地發現碰撞?指示示例代碼會很棒!快速Java圖像碰撞檢測算法

這裏是緩慢的算法,我現在用的是由像素像素去..

private boolean isPixelCollide(double x1, double y1, VolatileImage image1, 
       double x2, double y2, VolatileImage image2) { 

     double width1 = x1 + image1.getWidth() -1, 
       height1 = y1 + image1.getHeight() -1, 
       width2 = x2 + image2.getWidth() -1, 
       height2 = y2 + image2.getHeight() -1; 

      int xstart = (int) Math.max(x1, x2), 
       ystart = (int) Math.max(y1, y2), 
       xend = (int) Math.min(width1, width2), 
       yend = (int) Math.min(height1, height2); 

      // intersection rect 
      int toty = Math.abs(yend - ystart); 
      int totx = Math.abs(xend - xstart); 

      for (int y=1;y < toty-1;y++){ 
      int ny = Math.abs(ystart - (int) y1) + y; 
      int ny1 = Math.abs(ystart - (int) y2) + y; 

      for (int x=1;x < totx-1;x++) { 
       int nx = Math.abs(xstart - (int) x1) + x; 
       int nx1 = Math.abs(xstart - (int) x2) + x; 
       try { 
       if (((image1.getSnapshot().getRGB(nx,ny) & 0xFF000000) != 0x00) && 
        ((image2.getSnapshot().getRGB(nx1,ny1) & 0xFF000000) != 0x00)) { 
        // collide!! 
       return true; 
      } 
       } catch (Exception e) { 
//   System.out.println("s1 = "+nx+","+ny+" - s2 = "+nx1+","+ny1); 
       } 
      } 
      } 

      return false; 

}

+0

您正在爲所測試的每個像素*調用'image1.getSnapshot()'。拉出這個循環,至少...... – Marco13

回答

0

這是一個很大的getRGB的()。你有沒有考慮過代表魚雷和一艘船作爲箱子,並將它用於一些早期的拒絕機制?

另請嘗試將像素測試除以2.通過跳過每隔一個像素測試一半的分辨率。根據你的照片,半分辨率不應該是一個大問題。

1

您可以使用Rectangle類定義場景中每個對象的邊界,然後使用Rectangle#intersect(Rectangle Rect)方法。因此,您的相交方法可能如下所示:

private boolean intersect(double x1, double y1, VolatileImage image1, double x2, double y2, VolatileImage image2) { 
    return (new Rectangle(x1, y1, image1.getWidth(), image1.getHeight()).intersect(new Rectangle(x2, y2, image2.getWidth(), image2.getHeight())); 
} 
+0

這種方法被稱爲邊界框。如果OP使用它,則重要的是每個幀重用這些Rectangle實例,並將它們保存在它們各自的對象中。 –