2014-08-31 143 views
0

我正在寫一個SharpDx.Toolkit(XNA)遊戲。我搜索在互聯網上如何編程碰撞檢測,我發現這一點:碰撞檢測與旋轉的精靈SharpDX

static bool perPixel(Rectangle rectangleA, Color[] dataA, Rectangle rectangleB, Color[] dataB) 
     { 
      // Find the bounds of the rectangle intersection 
      int top = Math.Max(rectangleA.Top, rectangleB.Top); 
      int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom); 
      int left = Math.Max(rectangleA.Left, rectangleB.Left); 
      int right = Math.Min(rectangleA.Right, rectangleB.Right); 

      // Check every point within the intersection bounds 
      for (      
       int y = top; y < bottom; y++) 
      { 
       for (int x = left; x < right; x++) 
       { 
        if (dataA[(x - rectangleA.Left) + (y - rectangleA.Top) * rectangleA.Width] != new Color(0, 0, 0, 0) && dataB[(x - rectangleB.Left) + (y - rectangleB.Top) * rectangleB.Width] != new Color(0, 0, 0, 0)) 
        { 
         // Get the color of both pixels at this point 
         Color colorA = dataA[(x - rectangleA.Left) + 
              (y - rectangleA.Top) * rectangleA.Width]; 
         Color colorB = dataB[x - rectangleB.Left) + 
              (y - rectangleB.Top) * rectangleB.Width]; 

         // If both pixels are not completely transparent, 
         if (colorA.A != 0 && colorB.A != 0) 
         { 
          // then an intersection has been found 
          return true; 
         } 
        } 
       } 
      } 

      // No intersection found 
      return false; 
     } 

此代碼工作正常,但僅限於非旋轉精靈。所以我試圖添加一個矩陣變換,但它不起作用。

有沒有人有一個想法,如何做到這一點?

謝謝 基督教

編輯:遊戲是2D遊戲。

+0

你真的需要每個像素的碰撞嗎? – 2014-09-01 06:19:01

回答

1

在大多數情況下,每像素的碰撞是矯枉過正的,我不會推薦它用於編程實踐以外的任何事情。

您幾乎總是可以應用其他方法來查找引入更少錯誤並需要更少性能的colliss。

您可以使用物理引擎或找到其他方法。

一些方法,我相信,在您的情況下工作得很好:

  1. OBB-OBB碰撞
  2. 圈,圈碰撞

有了這些方法,你只檢查是否邊界相交,而不是檢查每一個像素對彼此。